返回"application/xml"而不是"text/plain"ASP.NET Core Web API

Dar*_*ric 11 xml asp.net-web-api asp.net-core

我有一个XML字符串,我需要将其作为XML文档返回.默认情况下,返回的内容类型为text/plain.内容已呈现,但我需要内容类型application/xml.我启用了RespectBrowserAcceptHeader选项,它将对象序列化为XML并设置正确的内容类型,除非对象是字符串.

[HttpGet]
public string Get()
{
   return xmlString;
}

public static string xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                     <sample>
                         Hello World.
                     </sample>";
Run Code Online (Sandbox Code Playgroud)

Sha*_*tin 20

简答

如果您有一个XML字符串并需要将其作为XML文档返回,则返回ContentResult.

[HttpGet]
public ContentResult Get()
{
    return new ContentResult
    {
        ContentType = "application/xml",
        Content = xmlString,
        StatusCode = 200
    };
}
Run Code Online (Sandbox Code Playgroud)

完整的例子

调节器

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
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

启动

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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": {}
  }
}
Run Code Online (Sandbox Code Playgroud)

响应

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>
Run Code Online (Sandbox Code Playgroud)

这是GitHub的好方法.:)

  • `[HttpGet, Produces("application/xml")] public ContentResult Get() { return Content(xmlString, "application/xml"); }`(抱歉格式很糟糕) (2认同)

Tse*_*eng 18

你可以这样做,return Content(xmlString, "application/xml")但这可能不是最好的方法,除非它们以这种方式存储在文件系统或数据库上.

通常,您希望拥有从您的操作返回的强类型类,并将它们序列化为xml.

您还可以根据accept标头(即json或xml)告诉您的操作返回内容,但对于xml,您需要首先注册xml序列化程序iirc.

services.AddMvc(...)
        .AddXmlSerializerFormatters()
        .AddXmlDataContractSerializerFormatters();
Run Code Online (Sandbox Code Playgroud)

并注释你的行为

[Produces("application/json", "application/xml")]
public Task<IActionResult> Get()
{
    User user = ...........;

    return ObjectResult(user);
}
Run Code Online (Sandbox Code Playgroud)

如果客户端发送Accept: application/xml然后它将返回xml,如果客户端发送Accept: application/json它返回json.