簡答
如果你有一個字符串,它是XML,並且需要將其返回爲一個XML文檔,然後返回一個ContentResult。
[HttpGet]
public ContentResult Get()
{
return new ContentResult
{
ContentType = "application/xml",
Content = xmlString,
StatusCode = 200
};
}
全部實施例
控制器
using Microsoft.AspNetCore.Mvc;
namespace MyXmlSample
{
[Route("xml")]
public class MyXmlController
{
public static string xmlString =
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<sample>
Hello World.
</sample>";
[HttpGet]
public ContentResult Get()
{
return new ContentResult
{
ContentType = "application/xml",
Content = xmlString,
StatusCode = 200
};
}
}
}
啓動
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace MyXmlSample
{
public class Program
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Program>()
.Build();
host.Run();
}
}
}
project.json
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNetCore.Mvc.Core": "1.0.0-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.NETCore.App": "1.0.0-rc2-*"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dnxcore50",
"portable-net45"
]
}
},
"runtimes": {
"win10-x64": {}
}
}
響應
HTTP/1.1 200 OK
Date: Sun, 17 Apr 2016 22:10:45 GMT
Content-Type: application/xml
Server: Kestrel
Content-Length: 75
<?xml version="1.0" encoding="UTF-8"?>
<sample>
Hello World.
</sample>
Here it is on GitHub的好辦法。 :)
您使用的是什麼版本的ASP.NET Core? –
' 「SDK」:{ 「版本」: 「1.0.0-RC1-UPDATE2」, 「運行」: 「coreclr」, 「架構」: 「64」 }'' – Daric
將ContentResult'爲工作太。 –