设置Web API响应的默认格式(ASP.NET Core)

时间:2017-12-09 22:16:11

标签: asp.net json xml asp.net-core asp.net-core-webapi

我在ASP.NET Core 2中有一个Web 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.xml时调用/GetValue.js和XML时,我仍然希望继续获取json

我找不到任何关于如何将XML作为默认格式的文档。 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

我们可以将默认值传递给占位符,因此我稍微更改了URL的格式并将其设置为:

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

然后/GetValue返回xml格式化的

/GetValue/xml返回xml格式的

/GetValue/js返回json格式化