Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using the newer ASP.NET Web API, in Chrome I am seeing XML - how can I change it to request JSON so I can view it in the browser? I do believe it is just part of the request headers, am I correct in that?

like image 215
naspinski Avatar asked Mar 23 '12 23:03

naspinski


People also ask

What is the best approach for requesting JSON instead of XML from an AP?

What is the best approach for requesting JSON instead of XML from an API? Add . json to the URL.

What is the default data return format in Web API?

By default Web API returns result in XML format.


2 Answers

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.

like image 123
Felipe Leusin Avatar answered Sep 25 '22 21:09

Felipe Leusin


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.

like image 28
Glenn Slaven Avatar answered Sep 23 '22 21:09

Glenn Slaven