Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

10 Answers

up vote 126 down vote accepted

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

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.

share|improve this answer
3  
good answer. much nicer than the higher voted one. – Sailing Judo Nov 6 '12 at 15:25
+1 good solution – TimDog Nov 27 '12 at 20:30
+1 nice solution. – plurby Jan 8 at 10:08
10  
Just to note, the original behaviour is correct. Chrome requests application/xml with a priority of 0.9 and */* with a priority of 0.8. By removing application/xml you remove the ability for the Web API to return XML if the client requests that specifically. e.g. if you send "Accept: application/xml" you will still receive JSON. – Porges Mar 26 at 21:20
2  
Is it me, or is the first sentence incorrect? The code appears to totally remove XML, not simply change the default. – Nick G Apr 9 at 18:24
show 3 more comments

MVC4 Quick Tip #3–Removing the XML Formatter from ASP.Net Web API

in Global.asax: add the line:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

like so:

        protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        BundleTable.Bundles.RegisterTemplateBundles();
        GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    }
share|improve this answer
7  
Works - much nicer having JSON be the default instead of XML. – Lee Whitney Apr 15 '12 at 22:38
but can you still return xml then? – Thomas Stock Jul 4 '12 at 0:37
25  
I tested it, and you can't. So this is removing XML support.. Ye be warned, dear google people – Thomas Stock Jul 4 '12 at 0:42
3  
If you have a look at my answer below, this will let xml still be returned if you want to but lets the site respond with JSON to the browser – Glenn Slaven Sep 24 '12 at 1:17
3  
@GlennSlaven yeah your answer should be the one marked as the correct one. – Floradu88 Oct 14 '12 at 16:46
show 4 more comments

In the Global.asax I am using the code below. My url to get JSON is http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}
share|improve this answer
Really useful during development when you spend much time in Chrome. – Luke Puplett Sep 3 '12 at 11:46
Great one. What is your method expect a parameter? like localhost:61044/api/values/getdate?json=true,date=2012-08-01 – LT.Nolo Sep 5 '12 at 13:04
excellent tip!! – Hor Sep 26 '12 at 20:58
Good one, Diganta Kumar. Btw, I reckon we've meet in #appfest. ;) – misaxi Mar 19 at 22:21

Have a look at content negotiation in the WebAPI. These (Part 1 & Part 2) wonderfully detailed and thorough blog posts explain how it works.

In short, you are right, and just need to set the Accept or Content-Type request headers. Given your Action isn't coded to return a specific format, you can set Accept: application/json.

share|improve this answer
2  
"so I can view it in the browser" – Spongman Mar 5 at 19:19

I just use

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.

share|improve this answer
I like this option it is not so heavy handed. – Eric Rohlfs Dec 19 '12 at 1:10
2  
This is a surprisingly overlooked answer, and although the original question wasn't totally clear, this directly makes JSON the default response for a web browser (which sends Accept: text/html). Good job. – gregmac Jan 15 at 1:44

One quick option is to use the MediaTypeMapping specialization. Here is an example of using QueryStringMapping in the Application_Start event:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("a", "b", "application/json"));

Now whenever the url contains the querystring ?a=b in this case, Json response will be shown in the browser.

share|improve this answer
1  
This was very useful. You can also use UriPathExtensionMapping instead of QueryStringMapping if you want to use path.to/item.json – Nuzzolilo Apr 13 '12 at 23:28
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

source: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

share|improve this answer
This is the most clean and short solution, thanks. – Denis Vuyka Feb 19 at 11:19

I find the Chrome app "Advanced REST Client" excellent for working with REST services. You can set the Content-Type to application/json among other things: https://chrome.google.com/webstore/detail/hgmloofddffdnphfgcellkdfbfbjeloo

share|improve this answer

Don't user your browser to test your api.

Instead, try to use an HTTP client that allows you to specify your request, such as CURL, or even Fiddler.

The problem of this issue is on the client... not on the api. The web api behaves accordingly the browser's request.

share|improve this answer
4  
Why not use the browser? It is an obvious tool for it. – Anders Lindén Sep 18 '12 at 6:37
        public HttpResponseMessage<SensorUpdate> Post(int id)
    {
        SensorUpdate su = new SensorUpdate();
        su.Id = 12345;            
        su.Username = "SensorUpdateUsername";
        su.Text = "SensorUpdateText";
        su.Published = DateTime.Now;


        HttpResponseMessage<SensorUpdate> response = new HttpResponseMessage<SensorUpdate>(su, 
                    new MediaTypeHeaderValue("application/json"));

        return response;
    }
share|improve this answer
1  
the System.Net.Http.Formatting assembly no longer contains the definition for HttpResponseMessage<T> – user1662812 Oct 3 '12 at 8:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.