设置 web API 响应的默认格式(ASP.NET 核心)
Set default format of web API response (ASP.NET Core)
我在 ASP.NET 核心 2 中有一个网络 API。我正在使用 https://andrewlock.net/formatting-response-data-as-xml-or-json-based-on-the-url-in-asp-net-core/
中定义的 FormatFilter
我有一个这样定义的函数:
[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 成为默认格式的文档。
我怎样才能做到这一点?
我们可以将默认值传递给占位符,所以我稍微更改了 URL 的格式,使其变成这样:
[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue/{format=xml}"), FormatFilter]
然后/GetValue
returnsxml格式化
/GetValue/xml
returns xml 格式化
/GetValue/js
returns json 格式化
我在 ASP.NET 核心 2 中有一个网络 API。我正在使用 https://andrewlock.net/formatting-response-data-as-xml-or-json-based-on-the-url-in-asp-net-core/
中定义的FormatFilter
我有一个这样定义的函数:
[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 成为默认格式的文档。 我怎样才能做到这一点?
我们可以将默认值传递给占位符,所以我稍微更改了 URL 的格式,使其变成这样:
[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue/{format=xml}"), FormatFilter]
然后/GetValue
returnsxml格式化
/GetValue/xml
returns xml 格式化
/GetValue/js
returns json 格式化