Author : Admin
Last Modified : 12-Sep-2021
Complexity : Beginner
Get ASP.NET Web API to return JSON instead of XML using Chrome
In your MVC Web API project
Add the following in App_Start / WebApiConfig.cs class in your 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.
Note: it can produce a XSS Vulnerability if you are using the default error handling of WebAPI.
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);
}
}