.Net Core 2接受XML返回406的标头

时间:2017-11-27 18:49:38

标签: xml rest api asp.net-core-2.0 request-headers

我已为我的API解决方案

添加了格式化输出和格式化为xml的输入
//add formatter to support XML media type results(application/xml)
setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
//add formatter to support XML media type request(application/xml)
setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());

但是当我使用application / xml的accept标头发出请求时,我得到一个406有没有其他人遇到过这个?

内容类型是application / json

----固定----

如果控制器动作返回的对象有一个构造函数,而accept头是application / xml,则响应将是406.只需删除构造函数然后我就可以返回XML。

3 个答案:

答案 0 :(得分:3)

re。 “如果控制器操作返回的对象具有构造函数,而accept标头为application / xml,则响应将为406。”实际上,这是不正确的。更正:“如果控制器操作返回的对象具有带参数的构造器,并且该对象也没有0参数的构造器,并且accept标头为application / xml,则响应将为406。“

答案 1 :(得分:1)

我遇到了同样的问题(.Net Core 2.2)。

由于此页面上的注释:https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.2

我检查了我的控制器是从Controller继承的,并且我的方法正在返回IActionResult。就是这种情况。

首先,我添加了此输出格式化程序:

  setupAction.OutputFormatters.Add(new XmlSerializerOutputFormatter());

尽管格式化程序位于outputformatters列表中且具有正确的MediaType,但该方法不起作用。

然后我改用首选的.Net 2.2方法:

        services.AddMvc(setupAction => 
        { 
               ...
        })
        .AddXmlSerializerFormatters();

仍然没有成功。

我回到“旧”方式并删除了AddXmlSerializerFormatters()并添加了

 setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());

即使用XmlDataContractSerializerOutputFormatter代替XmlSerializerOutputFormatter。

,然后它起作用了。

我花了一些时间找出差异,我的猜测是XmlSerializerOutputFormatter可以编写IEnumerable对象类型,而Customer是没有构造函数的POCO。

这是使用XmlSerializerOutputFormatter记录的内容 Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector:警告:找不到内容类型'application / xml'的输出格式化程序以写入响应。 Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor:警告:未找到内容类型'application / xml'的输出格式化程序来编写响应。

答案 2 :(得分:0)

Actually, I had the same problem, In my case I have a relationship in my tables, so, Entity Framework create a IEnumerable<Class> when you have HasMany, so what I did was just change my code 
from:
public ICollection<Credential> Credential { get; set; }

to:
public List<Credential> Credential { get; set; }

and Constructor from:
        public Personal()
        {
            Credential = new HashSet<Credential>();
        }
to:
        public Personal()
        {
            Credential = new List<Credential>();
        }
相关问题