pdube
pdube

Reputation: 633

Set default format of web API response (ASP.NET Core)

I have a web API in ASP.NET Core 2. I am using FormatFilter as defined in https://andrewlock.net/formatting-response-data-as-xml-or-json-based-on-the-url-in-asp-net-core/

I have a function defined like this:

[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue")]
[HttpGet("/api/Values/{userKey}/{variableKey}/GetValue.{format}"), FormatFilter]
public async Task<string> GetValue(string userKey, string variableKey)

In Startup I have:

    services.AddMvc(options =>
    {
        options.FormatterMappings.SetMediaTypeMappingForFormat("xml", "application/xml");
        options.FormatterMappings.SetMediaTypeMappingForFormat("js", "application/json");
    })
    .AddXmlSerializerFormatters();

It works fine except that I'd like the default format to be XML and not json when I call /GetValue.

I still wish to continue getting json when I call /GetValue.js and XML when I call /GetValue.xml

I cannot find any doc on how to make XML the default format. How can I achieve this?

Upvotes: 1

Views: 3016

Answers (1)

pdube
pdube

Reputation: 633

We can pass a default value to a placeholder, so I changed a little the format of the URL and made it like this:

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

Then /GetValue returns xml formatted

/GetValue/xml returns xml formatted

/GetValue/js returns json formatted

Upvotes: 2

Related Questions