【发布时间】:2018-05-23 20:17:51
【问题描述】:
我在 ASP.NET Core 2 中有一个 Web API。我正在使用 FormatFilter 中定义的 https://andrewlock.net/formatting-response-data-as-xml-or-json-based-on-the-url-in-asp-net-core/
我有一个这样定义的函数:
[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue")]
[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue.{format}"), FormatFilter]
public async Task<string> GetValue(string userKey, string variableKey)
在启动时我有:
services.AddMvc(options =>
{
options.FormatterMappings.SetMediaTypeMappingForFormat("xml", "application/xml");
options.FormatterMappings.SetMediaTypeMappingForFormat("js", "application/json");
})
.AddXmlSerializerFormatters();
它工作正常,只是我希望在调用 /GetValue 时默认格式为 XML 而不是 json。
我仍然希望在调用 /GetValue.js 时继续获取 json 并在调用 /GetValue.xml 时继续获取 XML
我找不到任何关于如何使 XML 成为默认格式的文档。 我怎样才能做到这一点?
【问题讨论】:
-
如何从控制器的操作中返回结果?
-
该函数返回一个简单的字符串,它正确地得到了 xml 或 json 格式。
-
也许您可以编写一个简单的中间件,如果 Accept.Content 标头未设置或不包含 application/json,则将 Accept-Content 标头强制为 application/xml
-
尝试清除格式化程序集合并以正确的顺序重新添加它们(首先默认然后其他)。 stackoverflow.com/questions/20191980/…
标签: asp.net json xml asp.net-core asp.net-core-webapi