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"));

3 comments:

  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
  2. Additional licenses have since been handed out and mobile/online wagering is also be|can be} accepted in-state. Following outcomes of the 2020 election, Maryland approved sports activities betting. Even although the Department of the Interior and the Seminole Tribe filed briefs in August 2022 to reinstate a new new} compact, discussions on the matter might not begin till summer 2023. On your first 5 deposits, use the casino bonus code WAGGINGTAILS for a 225% deposit match up to as} $2,250 온라인 카지노 on every.

    ReplyDelete
  3. Today there are 18 casinos working on this country with revenues reaching a complete of .5B. Only one of them – Kangwon Land casino is on the market for the citizens of South Korea. However, since Kangwon Land casino is situated in a distant area of South Korea and local gamblers can go to it only a hundred and eighty 카지노사이트 days per year, the KRW casinos stay probably the greatest gambling options for Koreans. There isn't any such thing as an online gambling age Korean players can begin taking part in} from since internet casinos are banned on this country. VPNs are also an possibility, depending on the site, as is cryptocurrency.

    ReplyDelete