ASP.NET Web API MediaTypeFormatter

What is MediaTypeFormatter?

MediaTypeFormatter is an abstract class from which JsonMediaTypeFormatter XmlMediaTypeFormatter classes inherit from. JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML. 

 


How to return only JSON from ASP.NET Web API Service irrespective of the Accept header value?

Include the following line in Register() method of WebApiConfig.cs file in App_Start folder. This line of code completely removes XmlFormatter which forces ASP.NET Web API to always return JSON irrespective of the Accept header value in the client request. Use this technique when you want your service to support only JSON and not XML. 


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


Similar way way can return only XML from ASP.NET Web API Service, add following line in Register() method of WebApiConfig.cs file in App_Start folder.


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

 

 


How to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser?


Approach 1 : Include the following line in Register() method of WebApiConfig.cs file in App_Start folder. This tells ASP.NET Web API to use JsonFormatter when a request is made for text/html which is the default for most browsers. The problem with this approach is that Content-Type header of the response is set to text/html which is misleading.


config.Formatters.JsonFormatter.SupportedMediaTypes

    .Add(new MediaTypeHeaderValue("text/html"));


Approach 2 : Include the following class in WebApiConfig.cs file in App_Start folder. 
public class CustomJsonFormatter : JsonMediaTypeFormatter

{

    public CustomJsonFormatter()

    {

        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

    }

 

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)

    {

        base.SetDefaultContentHeaders(type, headers, mediaType);

        headers.ContentType = new MediaTypeHeaderValue("application/json");

    }

}

 

 

ASP.NET Web API is an extinsible framework. This means you can also plugin your own custom formatter. For example, if you want the response to be in CSV format, you can create custom CSVMediaTypeFormatter that inherits from the base abstract class MediaTypeFormatter. 

Check below article for same,

 


Comments