Return json by default using ASP.NET Web API

Wesley Skeen picture Wesley Skeen · Dec 1, 2012 · Viewed 10.6k times · Source

Is it possible to return json by default from the ASP.NET Web API instead of XML?

Answer

tugberk picture tugberk · Dec 1, 2012

It's what is done by default. JsonMediaTypeFormatter is registered as the first MediaTypeFormatter and if the client doesn't request the response in a specific format, ASP.NET Web API pipeline gives you the response in application/json format.

If what you want is to only support application/json, remove all other formatters and only leave JsonMediaTypeFormatter:

public static void Configure(HttpConfiguration config) {

    var jqueryFormatter = config.Formatters.FirstOrDefault(x => x.GetType() == typeof(JQueryMvcFormUrlEncodedFormatter));
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);
    config.Formatters.Remove(jqueryFormatter);
}