我看到一些我根本不理解的ASP.NET核心行为。重申:
使用API模板创建一个新应用(现在使用Microsoft.AspNetCore.All 2.0.8
)。
按如下方式修改值控制器:
[HttpGet]
public IActionResult Get()
{
var xmlContent = new System.Xml.XmlDocument();
xmlContent.LoadXml("<MyData><StringProperty>foo</StringProperty></MyData>");
return new OkObjectResult(xmlContent);
}
运行应用程序并使用accept:application / xml例如
命中该APIGET http://localhost:3287/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:3287
Accept: application/xml
您将获得以下结果:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-Powered-By: ASP.NET
Date: Fri, 25 May 2018 22:55:00 GMT
Content-Length: 35
{"MyData":{"StringProperty":"foo"}}
客户端从服务器请求XML,服务器有XML结果,但返回了JSON。
我知道各种变通方法(例如使用ContentResult),但我想了解这是否是预期的行为,如果是,为什么?
答案 0 :(得分:0)
Andy Booth向我指出答案 - 需要像这样添加XmlSerializerFormatters:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddXmlSerializerFormatters();
}
完成此操作后,我得到了预期的行为:
GET http://localhost:3287/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:3287
Accept: application/xml
HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8
Server: Kestrel
X-Powered-By: ASP.NET
Date: Tue, 29 May 2018 19:45:48 GMT
Content-Length: 53
<MyData><StringProperty>foo</StringProperty></MyData>