forcing webapi return format

forcing webapi return format


I do a work everyday in my professional life in Microsoft’s ASP.NET application framework. In more recent year I started utilizing more and more WEBAPI call through jQuery calls instead of trying to load data during a page’s Page_Load event. WEBAPI handles a lot of the conversions of datatypes to JSON (JavaScipt Object Notation) format for you. Sometimes I have simple calls that can be called directly from typing the URL into the browser and passing values through the use of the QueryString parameters. The idea being I could quickly test a WEBAPI call by typing a URL directly into the browser and making sure it’s working correct. Usually doing this returns the value in XML format and not the JSON format that I would expect when I call it from a jQuery Ajax call. I know I could use a utility like POSTMAN, which I love, but it just seems like I should be able to type the URL while I’m running the application in Visual Studio and get the results the way I want it.


I ran across and article on how to solve this problem. Adding this code into my application startup allows my to add a type parameter to the QueryString to force the format I want.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add( new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json"))); 

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add( new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml"))); 


This little gem of code adds a QueryString parameter to a media type header value auto-magically. If I had a fictitious WEBAPI controller that returns detail for a customer record with an id of 100 that looks something like this:

I could just append a ?type=json to then to force the return value to json without ever leaving the browser debug session I’m working in.

Pretty Cool!