By default, Web API returns both XML and JSON depending the the client. You the specifically specify what format you return.

Bounding WebAPI to send only json formatted data

Now there are cases where we want our application to receive only JSON formatted data irrespective of the ACCEPT header value. To achieve this, add a below line in App_Start > WebApiConfig.cs> Register method.

config.Formatters.Remove(config.Formatters.XmlFormatter);

This will remove the XML formatter and always return JSON data. 

Similarly to get data in only XML format, below is the code.

config.Formatters.Remove(config.Formatters.JsonFormatter);

Returning data based upon the accept header

For this purpose, add the below line of code in App_Start> WebApiConfig.cs> Register method

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

Sources:

https://www.dotnettricks.com/learn/webapi/content-negotiation-in-asp-net-web-api

Last modified: December 11, 2020

Author

Comments

Write a Reply or Comment