简答
如果您有一个 XML 字符串并且需要将其作为 XML 文档返回,则返回内容结果 https://github.com/aspnet/Mvc/blob/a60cce1dade062454f106a1317fc198fc8778035/src/Microsoft.AspNetCore.Mvc.Core/ContentResult.cs.
[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
};
}
}
}
Startup
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();
}
}
}
项目.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": {}
}
}
Response
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>
这是在 GitHub 上的 https://github.com/bigfont/StackOverflow/tree/master/AspNetCoreApiReturnXmlString为了更好的衡量。 :)