1

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?

4
  • How are you returning results from controller's action? Commented Dec 9, 2017 at 22:33
  • The function returns a simple string, which correctly gets xml or json formatted. Commented Dec 9, 2017 at 22:35
  • maybe you can write a simple middleware that force the Accept-Content header to application/xml if the Accept.Content header is not set or doesn't contains application/json Commented Dec 9, 2017 at 23:27
  • Try clearing formaters collection and add them back in right order (first default then other). stackoverflow.com/questions/20191980/… Commented Dec 10, 2017 at 7:34

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.