Thursday, March 1, 2012

Force the .net Web Api to return JSON to the browser by default.

Even though by default the Web Api has Json set as the first formatter, if you hit your Api in a browser it will attempt to return Xml. This is because Chrome and other browsers have a default accept header that looks something like:

    Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8


The Json formatter is only looking for an "application/json" or similar accept header and so is skipped over, triggering the Xml formatter when it sees the "application/xml" accept header.

You could clear the SupportedMediaTypes from the XmlFormatter (in Application_Start):


    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


But then no one would get Xml. So, easy peasy, just add "text/html" to the JsonFormatters supported media types and you get Json in the browser, but if someone really wants "application/xml" they can get that too by only requesting the appropriate type.

You can doublecheck in the debugger that Json is the first formatter, but this worked for me:


    GlobalConfiguration.Configuration.Formatters[0] .SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

1 comment:

  1. Why not just GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));?

    This protects you in case the order of the formatters changes at some point in the future.

    ReplyDelete