16

I have a Web API project that returns some product data. It negotiates the return type correctly depending on the Accept header (JSON/XML) of the request. The problem is, if no Accept header is specified it returns JSON, but I want it to return XML by default. How do I change the content negotiation defaults in Global.asax?

1 Answer 1

32

Found a solution via http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/

Added this in WebApiConfig.Register():

config.Formatters.Clear();
config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.Add(new FormUrlEncodedMediaTypeFormatter());

So default is XML, the first formatter, but the API still supports JSON if the request asks for it.

3
  • 1
    Also add FormUrlEncodedMediaTypeFormatter in your above code as by default Web API has that formatter too in the collection
    – Kiran
    Nov 25, 2013 at 17:40
  • what this FormUrlEncodedMediaTypeFormatter does?? I see that returns nothing! Jul 18, 2014 at 7:38
  • @Sunny it should return URL formatted values (msdn.microsoft.com/en-us/library/…) like myVariable=1&myOtherVariable=test
    – Edgar
    Jul 18, 2014 at 8:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.