Search code examples
asp.net-web-apimediatypeformatter

Return json by default using ASP.NET Web API


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


Solution

  • 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);
    }