【问题标题】:Set default format of web API response (ASP.NET Core)设置 Web API 响应的默认格式 (ASP.NET Core)
【发布时间】: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


【解决方案1】:

我们可以将默认值传递给占位符,所以我稍微改变了 URL 的格式,使其如下:

[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue/{format=xml}"), FormatFilter]

然后/GetValue返回xml格式

/GetValue/xml 返回 xml 格式

/GetValue/js 返回 json 格式

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 2022-11-08
    • 1970-01-01
    • 2019-08-20
    • 2021-03-01
    • 1970-01-01
    • 2020-03-23
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多