Preventing WebAPI from Serializing Model Objects into XML

One good thing about WebAPI is it's flexibility. Depending on the value of the Accept header in the HTTP request, WebAPI determines which serialization format to use when serializing model objects. If you use a browser to reach to a method on a WebAPI controller, it is most likely going to return XML representation of your model data because the browser  would set Accept header value to something like the following …

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

But, you can configure WebAPI to return JSON regardless of what value is present in Accept header. That requires you to change the global configuration object. Add the following 2 lines at the end of the Application_Start() method in the Global.asax.cs file to allow WebAPI to always serialize model objects into JSON format.

var globalConfig = GlobalConfiguration.Configuration;


Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now