无法在 ASP.NET Core 2 中序列化为 XML

Cannot serialise to XML in ASP.NET Core 2

目前,我对基本的 ASP.NET 核心 2 API 项目和内容协商以及 return JSON 之外的内容感到非常困惑。

我以前在 1.1 项目中有过此工作,但在 2 中没有。我基本上想 return 某些东西,如 JSON 或 XML,具体取决于请求类型。

作为该要求的一部分,我设置了 XML 格式化程序,如下所示:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.ReturnHttpNotAcceptable = true;
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
        });
    }

我也可以使用 AddXmlSerializerFormatters() 但相同的区别(并尝试过)。这是我在无数例子中看到和以前做过的方式。

我有一个控制器和一个动作,基本上是这样的:

[Route("api/[controller]")]
public class DefaultController : Controller
{
    [HttpGet]
    [Route("")]
    public IActionResult Index()
    {
        return Ok(new
        {
            success = true
        });
    }
}

现在当我 运行 我在 Postman 中得到这个:

{"success": true}

所以它适用于(或至少默认)JSON。

然后,如果我使用 header Accept: application/xml 请求,我现在会收到 HTTP 错误 406。

如果我起飞options.ReturnHttpNotAcceptable = true;,无论如何都会returnJSON。

我错过了什么?我坐在那里挠头。据我所知,我已经注册了一个可接受的内容格式化程序。

您看到的问题是匿名类型无法序列化为 XML,因此格式化程序失败并退回到 JSON 格式化程序。

解决方法:当你需要return XML.

时使用类

There is already open issue for that.

作为解决方法,尝试将此选项添加到 Mvc:

options.FormatterMappings.SetMediaTypeMappingForFormat("xml", "text/xml");

具有 [FormatFilter] 属性

正如@So 以前说的好,匿名类型不能序列化成XML。这是我的例子:

[AllowAnonymous]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ProducesResponseFormatController : ControllerBase {
    [HttpGet]
    [Produces("application/xml")]
    public IActionResult Get() {
        // this worked well
        return Ok(new Model.appsettings.TokenSettings()); 

        // this didn't
        return Ok(new { A = new { B = "b inside a", C = "C inside A" }, D = "E" }); 
    }
}