How do I get ASP.NET Web API to return JSON instead of XML using Chrome? How do I get ASP.NET Web API to return JSON instead of XML using Chrome? google-chrome google-chrome

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?


Note: Read the comments of this answer, it can produce a XSS Vulnerability if you are using the default error handing of WebAPI

I just add the following in App_Start / WebApiConfig.cs class in my MVC Web API project.

config.Formatters.JsonFormatter.SupportedMediaTypes    .Add(new MediaTypeHeaderValue("text/html") );

That makes sure you get JSON on most queries, but you can get XML when you send text/xml.

If you need to have the response Content-Type as application/json please check Todd's answer below.

NameSpace is using System.Net.Http.Headers.


If you do this in the WebApiConfig you will get JSON by default, but it will still allow you to return XML if you pass text/xml as the request Accept header.

Note: This removes the support for application/xml

public static class WebApiConfig{    public static void Register(HttpConfiguration config)    {        config.Routes.MapHttpRoute(            name: "DefaultApi",            routeTemplate: "api/{controller}/{id}",            defaults: new { id = RouteParameter.Optional }        );        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);    }}

If you are not using the MVC project type and therefore did not have this class to begin with, see this answer for details on how to incorporate it.


Using RequestHeaderMapping works even better, because it also sets the Content-Type = application/json in the response header, which allows Firefox (with JSONView add-on) to format the response as JSON.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",                               "text/html",                              StringComparison.InvariantCultureIgnoreCase,                              true,                               "application/json"));


matomo