By naspinski


2012-03-23 23:04:12 8 Comments

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?

29 comments

@dmit77 2014-09-26 20:48:13

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"));

@Steve Johnson 2015-03-07 21:06:41

This is the most lean and simplest solution and Fiddler also detects the content type being returned as josn.

@Tim Abell 2015-05-22 02:40:57

Nice! Where would you suggest putting this in the code?

@Animesh 2015-06-25 08:11:16

It should go in WebApiConfig.cs

@KingOfHypocrites 2015-07-06 15:47:01

Also a great fix for the jsonformatter extension which breaks without this.

@KingOfHypocrites 2015-07-06 15:50:09

for some reason though the jsonp formatter extension breaks though when doing this... github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp

@bbsimonbb 2016-02-09 10:03:33

Worked for me. I needed to add a using System.Net.Http.Formatting;

@shuniar 2016-08-18 20:22:44

This should be the accepted answer IMO since it returns application/json instead of text/html.

@BrainSlugs83 2017-05-05 16:03:09

Linking for my own convenience: This answer plays nicely with another setup step I usually perform: stackoverflow.com/a/28337589/398630.

@Phileosophos 2017-09-13 16:24:29

And to be clear, this just changes the default. You can always get either JSON or XML simply by including the relevant "Accept" header.

@Avinash Patil 2019-05-16 23:35:55

It works great for JSON but it does not return properly formatted XML.

@Charles Burns 2018-04-13 19:42:40

Using Felipe Leusin's answer for years, after a recent update of core libraries and of Json.Net, I ran into a System.MissingMethodException:SupportedMediaTypes. The solution in my case, hopefully helpful to others experiencing the same unexpected exception, is to install System.Net.Http. NuGet apparently removes it in some circumstances. After a manual installation, the issue was resolved.

@Akshay Kapoor 2018-04-11 10:21:38

You can use as below:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

@allen1 2018-12-31 20:35:44

If you're making a WebAPI app for just passing JSON messages, consider this answer.

@user3285954 2017-11-30 23:01:52

I'm astonished to see so many replies requiring coding to change a single use case (GET) in one API instead of using a proper tool what has to be installed once and can be used for any API (own or 3rd party) and all use cases.

So the good answer is:

  1. If you only want to request json or other content type install Requestly or a similar tool and modify the Accept header.
  2. If you want to use POST too and have nicely formatted json, xml, etc. use a proper API testing extension like Postman or ARC.

@user3285954 2017-12-06 20:33:18

Dear anonymous downvoter, please explain why this isn't a good answer.

@Felipe Leusin 2012-11-07 20:25:25

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;

@Eric Rohlfs 2012-12-19 01:10:55

I like this option it is not so heavy handed.

@gregmac 2013-01-15 01:44:29

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.

@tponthieux 2013-08-15 01:34:10

I like this much better than requiring a json=true query parameter.

@Derek Hunziker 2013-11-16 09:51:22

+1 Far and away the best answer. I imagine there are a ton of ppl who opt to completely remove XML just because they don't see JSON in the browser.

@Todd Menier 2013-12-12 23:54:46

Well done. My answer expands on this a bit by accepting text/html but returning application/json, in case you happen to use a Chrome extension that expects it for formatting.

@surfmuggle 2013-12-13 13:21:37

@Felipe: Did you add your line above into the Global.asax? Do you mean: GlobalConfiguration.Configuration.Formatters.JsonFormatter.S‌​upportedMediaTypes.A‌​dd(new MediaTypeHeaderValue("text/html"));?

@Felipe Leusin 2013-12-13 22:11:02

I haven't worked with WebAPI for a while but i'm pretty sure that's it.

@Stonetip 2014-03-14 15:03:19

I found when I did this that data provided by a third party with HTML break tags in it ended up with carriage returns. The JSON was then invalid. Better to use the accepted answer if this affects you.

@Mrchief 2014-05-02 17:29:38

Note that the response's Content-Type header will still be text/html.

@user20358 2014-07-02 08:45:57

why text/html? Isn't the type for json: application/json ? When I used the solution above and put application/json instead of text/html, I got the response in XML. Isn't this counter intuitive? application/json should have worked. What is the reasoning for this?

@meffect 2014-07-10 21:01:52

This is horrible. The response content type header should be application/json. This "solution" makes it text/html.

@Felipe Leusin 2014-07-11 14:40:49

This was the solution to display on chrome. While not perfect it fits, in case you need the Content-Type as application/json you can check Todd's answer.

@Curtis Yallop 2015-05-20 22:02:03

Note that if the request "Accept" header field is "application/json" (ie set in an ajax GET request), it should return json back. Mine does this but displays xml if you open the url in chrome (where request accept is not set to json).

@sabdiel 2015-07-16 17:38:57

In my case not configuration was needed json serialization was in place by default. Based on the content negotiation rules if there is not agreement the content will be converted into json.

@kipusoep 2015-12-28 13:14:42

This answer is even better: stackoverflow.com/a/26068063/510149

@ComeIn 2016-04-25 08:37:21

And 926 people upvoted it ?????

@Eugene 2016-05-30 12:55:53

In case you want to lock down to json only, I suggest you clear all formaters and enable Json only. GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

@BBi7 2016-07-16 03:31:04

I'm annoyed that Stack Overflow doesn't allow me to take back my upvote because this is not what I'm looking for. Cameln, probably because people jump the gun thinking this solution is correct. Why is MS not setting this up properly with JSON by default? I've done this through a Certified Microsoft class and will I'll try to locate the proper solution.

@SO used to be good 2017-01-11 19:53:49

Why/How would JSON support HTML?

@Adam Cox 2017-04-03 15:43:45

None of this worked for me. I ended up doing this.

@pavan kumar 2017-04-13 06:30:59

or you can do config.Formatters.Remove(config.Formatters.XmlFormatter); since JSON is the default format

@BrainSlugs83 2017-05-05 16:05:21

Only 40 people noticed that there's a way better answer. (via @meffect just remap the response type instead of setting the wrong default.)

@user3285954 2017-11-30 23:06:56

This is a stupid hack, not a good answer. Why would one modify their code for something so simple as setting a request header? If you are so keen on writing code for this rather recommend writing tests. And I guess naspinski and others realized that they can't test POST, PUT, DELETE etc with a plain browser.

@Doug McClean 2017-12-27 23:41:41

This answer could potentially expose an XSS vulnerability. WebAPI will include the full URL on a 404 response, and because the content type is text/html, the browser will happily execute any JavaScript included in the query string.

@JPatel 2018-01-05 07:25:47

For detailed configuration, one can look at reference: docs.microsoft.com/en-us/aspnet/web-api/overview/…

@Majedur Rahaman 2019-01-14 08:18:46

Just add this code in webconfig.cs file var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDe‌​fault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(ap‌​pXmlType);

@Gaurav Dubey 2017-07-01 04:31:36

        config.Formatters.Remove(config.Formatters.XmlFormatter);

@S.R 2017-07-01 04:52:34

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this stackoverflow.com/help/how-to-answer

@pavan kumar 2017-04-13 06:26:19

Most of the above answers makes perfect sense. Since you are seeing data being formatted in XML format ,that means XML formatter is applied,SO you can see JSON format just by removing the XMLFormatter from the HttpConfiguration parameter like

public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );                
            config.Formatters.Remove(config.Formatters.XmlFormatter);                
            config.EnableSystemDiagnosticsTracing();
        }

since JSON is the default format

@Emil Pedersen 2017-06-01 14:01:14

This should be the correct answer

@Chaki_Black 2017-12-28 09:29:45

Oh, it is what I needed!

@Stacked 2016-12-08 19:03:45

Returning the correct format is done by the media-type formatter. As others mentioned, you can do this in the WebApiConfig class:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        // Configure Web API to return JSON
        config.Formatters.JsonFormatter
        .SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

        ...
    }
}

For more, check:

In case your actions are returning XML (which is the case by default) and you need just a specific method to return JSON, you can then use an ActionFilterAttribute and apply it to that specific action.

Filter attribute:

public class JsonOutputAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
        var value = content.Value;
        Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];

        var httpResponseMsg = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            RequestMessage = actionExecutedContext.Request,
            Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
        };

        actionExecutedContext.Response = httpResponseMsg;
        base.OnActionExecuted(actionExecutedContext);
    }
}

Applying to action:

[JsonOutput]
public IEnumerable<Person> GetPersons()
{
    return _repository.AllPersons(); // the returned output will be in JSON
}

Note that you can omit the word Attribute on the action decoration and use just [JsonOutput] instead of [JsonOutputAttribute].

@Nick 2015-10-09 16:19:05

It's unclear to me why there is all of this complexity in the answer. Sure there are lots of ways you can do this, with QueryStrings, headers and options... but what I believe to be the best practice is simple. You request a plain URL (ex: http://yourstartup.com/api/cars) and in return you get JSON. You get JSON with the proper response header:

Content-Type: application/json

In looking for an answer to this very same question, I found this thread, and had to keep going because this accepted answer doesn't work exactly. I did find an answer which I feel is just too simple not to be the best one:

Set the default WebAPI formatter

I'll add my tip here as well.

WebApiConfig.cs

namespace com.yourstartup
{
  using ...;
  using System.Net.Http.Formatting;
  ...
  config.Formatters.Clear(); //because there are defaults of XML..
  config.Formatters.Add(new JsonMediaTypeFormatter());
}

I do have a question of where the defaults (at least the ones I am seeing) come from. Are they .NET defaults, or perhaps created somewhere else (by someone else on my project). Anways, hope this helps.

@Diganta Kumar 2012-07-06 07:00:34

In the Global.asax I am using the code below. My URI 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"));
}

@LT.Nolo 2012-09-05 13:04:26

Great one. What is your method expect a parameter? like localhost:61044/api/values/getdate?json=true,date=2012-08-01

@Thomas 2013-11-12 10:40:13

what kind of format of data web api return by default. is it json or webapi ? thanks

@Michael Vashchinsky 2013-01-05 22:43:37

In the WebApiConfig.cs, add to the end of the Register function:

// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

Source.

@Glenn Slaven 2013-07-31 22:41:13

Is XmlFormatter new in MVC4?

@Steven 2013-09-19 13:50:37

In MVC5, this can be done by replacing config with GlobalConfiguration.Configuration

@Luc C 2014-07-15 12:45:52

For a project that must support JSON only and under no circumstance can be allowed to emit XML this is by far the best option.

@Cas Bloem 2015-04-16 13:41:22

config.Formatters.Add(config.Formatters.JsonFormatter);

@BrainSlugs83 2017-05-05 21:30:14

That's terrible. -- This will always return JSON no matter what, even if the client specifically asks for XML in the Content-Type header.

@Md. Sabbir Ahamed 2016-11-10 11:11:24

Just add those two line of code on your WebApiConfig class

public static class WebApiConfig
{
     public static void Register(HttpConfiguration config)
     {
          //add this two line 
          config.Formatters.Clear();
          config.Formatters.Add(new JsonMediaTypeFormatter());


          ............................
      }
}

@A.T. 2016-10-27 10:26:57

as per latest version of ASP.net WebApi 2,

under WebApiConfig.cs , this will work

config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);

@rocky_pps 2016-09-25 00:13:10

WebApiConfig is the place where you can configure whether you want to output in json or xml. by default it is xml. in the register function we can use HttpConfiguration Formatters to format the output . System.Net.Http.Headers => MediaTypeHeaderValue("text/html") is require to get the output in the json format. enter image description here

@jayson.centeno 2013-09-03 01:48:02

This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true.

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Thanks everyone!

@raider33 2014-03-30 14:04:24

This is the most flexible answer (and really should be the default configuration these days). To add to this answer, JSON is the default, including from browser. To view XML, add query string: ?xml=true

@pat capozzi 2015-06-17 21:55:11

Tried a number of strategies. Had a simple test for both XML and JSON and this worked out of the box

@Vikas Bansal 2016-05-28 10:49:51

Here is the easiest way that I have used in my applications. Add given below 3 lines of code in App_Start\\WebApiConfig.cs in Register function

    var formatters = GlobalConfiguration.Configuration.Formatters;

    formatters.Remove(formatters.XmlFormatter);

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

Asp.net web API will automatically serialize your returning object to JSON and as the application/json is added in the header so the browser or the receiver will understand that you are returning JSON result.

@vaheeds 2016-02-08 05:03:12

You just change the App_Start/WebApiConfig.cs like this:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        //Below formatter is used for returning the Json result.
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        //Default route
        config.Routes.MapHttpRoute(
           name: "ApiControllerOnly",
           routeTemplate: "api/{controller}"
       );
    }

@naspinski 2016-02-08 15:36:02

Removing a formatter is generally not a good idea, you are removing functionality.

@vaheeds 2016-02-08 19:03:21

Actually in this case, it works well for me, also many others suggest a way like this. I've learned it from myview.rahulnivi.net/building-spa-angular-mvc-5 book!

@vaheeds 2016-02-08 19:05:33

going ahead and vote down is not a good idea as well!

@Illuminati 2016-02-21 06:55:07

@naspinski , if you are voting down better explain the correct reason. just stating the obvious "removing the functionality" doesn't help. in fact this method was first recommended by Scott Hanselman, so would you care to provide your evidence that this is wrong ?

@Dan Bechard 2016-04-18 16:00:52

@naspinski Removing functionality is only "not a good idea" when you need that functionality. If you don't need it, then removing it is a great idea because is simplifies your application, reduces the size of the output, and possibly even improves performance.

@mdisibio 2016-01-12 17:06:28

Here is a solution similar to jayson.centeno's and other answers, but using the built-in extension from System.Net.Http.Formatting.

public static void Register(HttpConfiguration config)
{
    // add support for the 'format' query param
    // cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx
    config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
    config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");

    // ... additional configuration
 }

The solution was primarily geared toward supporting $format for OData in the early releases of WebApi, but it also applies to the non-OData implementation, and returns the Content-Type: application/json; charset=utf-8 header in the response.

It allows you to tack &$format=json or &$format=xml to the end of your uri when testing with a browser. It does not interfere with other expected behavior when using a non-browser client where you can set your own headers.

@rism 2015-12-06 06:32:26

Some time has passed since this question was asked (and answered) but another option is to override the Accept header on the server during request processing using a MessageHandler as below:

public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
    {
        var someOtherCondition = false;
        var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
        if (someOtherCondition && accHeader.Contains("application/xml"))
        {
            request.Headers.Remove("Accept");
            request.Headers.Add("Accept", "application/json");
        }
        return await base.SendAsync(request, cancellationToken);
    }
}

Where someOtherCondition can be anything including browser type, etc. This would be for conditional cases where only sometimes do we want to override the default content negotiation. Otherwise as per other answers, you would simply remove an unnecessary formatter from the configuration.

You'll need to register it of course. You can either do this globally:

  public static void Register(HttpConfiguration config) {
      config.MessageHandlers.Add(new ForceableContentTypeDelegationHandler());
  }

or on a route by route basis:

config.Routes.MapHttpRoute(
   name: "SpecialContentRoute",
   routeTemplate: "api/someUrlThatNeedsSpecialTreatment/{id}",
   defaults: new { controller = "SpecialTreatment" id = RouteParameter.Optional },
   constraints: null,
   handler: new ForceableContentTypeDelegationHandler()
);

And since this is a message handler it will run on both the request and response ends of the pipeline much like an HttpModule. So you could easily acknowledge the override with a custom header:

public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
    {
        var wasForced = false;
        var someOtherCondition = false;
        var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
        if (someOtherCondition && accHeader.Contains("application/xml"))
        {
            request.Headers.Remove("Accept");
            request.Headers.Add("Accept", "application/json");
            wasForced = true;
        }

        var response =  await base.SendAsync(request, cancellationToken);
        if (wasForced){
          response.Headers.Add("X-ForcedContent", "We overrode your content prefs, sorry");
        }
        return response;
    }
}

@Mike Rowley 2012-03-28 21:57:46

I found the Chrome app "Advanced REST Client" excellent to work with REST services. You can set the Content-Type to application/json among other things: Advanced REST client

@Todd Menier 2013-12-12 23:52:05

I like Felipe Leusin's approach best - make sure browsers get JSON without compromising content negotiation from clients that actually want XML. The only missing piece for me was that the response headers still contained content-type: text/html. Why was that a problem? Because I use the JSON Formatter Chrome extension, which inspects content-type, and I don't get the pretty formatting I'm used to. I fixed that with a simple custom formatter that accepts text/html requests and returns application/json responses:

public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
    public BrowserJsonFormatter() {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        this.SerializerSettings.Formatting = Formatting.Indented;
    }

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
}

Register like so:

config.Formatters.Add(new BrowserJsonFormatter());

@Alastair Maw 2014-05-15 14:48:49

In the constructor add this.SerializerSettings.Formatting = Formatting.Indented; if you want it pretty-printed without a browser extension.

@Nick 2014-07-01 17:49:27

Perfect. I was having issues with Felipe's solution returning a Content-Type of text/html and this fixed it (and made the response correct!) I combined your answer with suhair's answer so that I get JSON sent to the browser by default but have the option of adding "format=xml" or "format=json" to the querystring to select a specific formatter. Thanks!

@meffect 2014-07-10 21:04:56

why would you want it to pretty print over the wire?

@eddiegroves 2014-07-21 06:20:23

@meffect pretty-printing is preferred when viewing in a browser. Clients requesting json via application/json would still have non indented json returned.

@H.Wolper 2014-12-01 12:00:58

Isn't @dmit77 's Answer better (more concise) than this one?

@Todd Menier 2014-12-15 18:31:36

@AlastairMaw good idea, added your suggestion so pretty-printing works without the browser extension.

@meffect 2015-02-12 20:53:32

@eddiegroves you dont want pretty-print over the wire. You want the server to send the least amount of bits over the wire (ie: no spaces). Then you want the browser to format it nicely, with addons and such. Javascript needs to parse the JSON usually, why make it slower by introducing unnecessary formatting

@Jester 2015-09-03 20:10:48

Thanks Todd, best answer: 1) Correct return type, 2) keeps pretty formatting ONLY from a browser AND 3) I don't have to add a new accept type to Firefox and Chrome works also! Sweetness.

@Berriel 2015-09-16 01:46:45

For the googlers who are looking for: don't forget to add using System.Net.Http.Formatting and using Newtonsoft.Json

@unruledboy 2015-10-28 03:17:13

why I use other clients like DHC chrome extension to do restful API call by passing "Accept" as "application/xml", it is still giving the same error, either Felipe's or yours solution?

@wize 2016-01-26 19:49:57

To make sure international characters are returned correcty, set the correct charset by adding the line headers.ContentType.CharSet = "utf-8"; to the bottom of SetDefaultContentHeaders() function.

@Paul 2016-02-12 18:25:14

What is the best folder / file to place BrowserJsonFormatter class in ASP.NET MVC4 application? I placed it in WebApiConfig.cs file, but am feeling it is not the right way.

@async 2016-06-08 05:59:26

@meffect You're right. However you may want to have that option available in Debug builds. That's what I do.

@DonDon 2016-11-24 06:09:25

The solution doesn't work with IE (e.g. still asking to download json file). Any fix for this ?

@Adam Cox 2017-04-03 15:56:07

This didn't work for me, so I ended up doing this.

@Jay Shah 2017-06-13 11:24:04

@ToddMenier - Please let me know if you have any idea on setting default content type header for .Net Core

@lko 2014-09-30 19:19:10

From MSDN Building a Single Page Application with ASP.NET and AngularJS (about 41 mins in).

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // ... possible routing etc.

        // Setup to return json and camelcase it!
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    }

It should be current, I tried it and it worked.

@lko 2016-10-19 18:15:55

Care to comment on the downvote?

@Stacked 2016-12-09 16:24:56

It's nice to know why people downvoted your question or answer, but it's not an obligation, users are free whether to leave a comment or not. You can read more here. BTW, I'm not the downvoter :)

@dmyoko 2012-07-15 00:24:16

Don't use 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 with this issue is in the client, not in the API. The web API behaves correctly, according to the browser's request.

@Anders Lindén 2012-09-18 06:37:28

Why not use the browser? It is an obvious tool for it.

@Ivaylo Slavov 2014-04-25 21:30:27

I think the point here is correct and important - we should not overfix a working part of the application (the MVC WebAPI infrastructure) if the problem is caused by the client. The real use case for an Api is to be properly used (by supplying correct headers), which is responsibility of the application. I disagree with completely discarding the browser though - for testing, there are plenty of tools for almost any browser (Rest Client-like extensions to start with).

@bonh 2015-05-14 19:14:18

This should probably be a comment.

@Chris S 2013-09-27 10:40:29

As the question is Chrome-specific, you can get the Postman extension which allows you to set the request content type.

Postman

@Bjartur Thorlacius 2018-06-06 10:48:20

In Firefox, simply go to about:config, search for accept.default and change the content of the network.http.accept.default configuration to text/html,application/xhtml+xml,application/json;q=0.9,appli‌​cation/xml;q=0.8,*/*‌​;q=0.7.

@Bjartur Thorlacius 2018-06-06 11:01:10

Or better yet, just text/html,application/xhtml+xml;q=1.0,*/*;q=0.7 to avoid buggy hosts such as Bitbucket from accidentally serving your browser JSON in lieu of HTML.

@Falcon Momot 2018-07-02 04:34:34

The URL is dead. A new one is chrome.google.com/webstore/detail/postman/….

@Yakir Manor 2012-04-02 16:11:04

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

@whitneyland 2012-04-15 22:38:32

Works - much nicer having JSON be the default instead of XML.

@Thomas Stock 2012-07-04 00:37:15

but can you still return xml then?

@Thomas Stock 2012-07-04 00:42:37

I tested it, and you can't. So this is removing XML support.. Ye be warned, dear google people

@Glenn Slaven 2012-09-24 01:17:22

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

@radu florescu 2012-10-14 16:46:05

@GlennSlaven yeah your answer should be the one marked as the correct one.

@shashwat 2013-02-21 15:14:23

Adding only last line GlobalConfiguration.Configuration.Formatters.XmlFormatter.Su‌​pportedMediaTypes.Cl‌​ear(); worked for me. I was getting error in all other lines. It is Web Form Apllication

@Adam Cox 2017-04-03 15:59:24

Tried this too, but didn't work. I ended up doing this.

@Roger Lipscombe 2013-06-23 14:47:02

I used a global action filter to remove Accept: application/xml when the User-Agent header contains "Chrome":

internal class RemoveXmlForGoogleChromeFilter : IActionFilter
{
    public bool AllowMultiple
    {
        get { return false; }
    }

    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(
        HttpActionContext actionContext,
        CancellationToken cancellationToken,
        Func<Task<HttpResponseMessage>> continuation)
    {
        var userAgent = actionContext.Request.Headers.UserAgent.ToString();
        if (userAgent.Contains("Chrome"))
        {
            var acceptHeaders = actionContext.Request.Headers.Accept;
            var header =
                acceptHeaders.SingleOrDefault(
                    x => x.MediaType.Contains("application/xml"));
            acceptHeaders.Remove(header);
        }

        return await continuation();
    }
}

Seems to work.

@Glenn Slaven 2012-09-19 02:53:19

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.

@porges 2013-03-26 21:20:29

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.

@Sylvain 2013-03-29 16:38:00

Based on @Porges's comment, I suggest wrapping the two lines that remove XML support in a #if DEBUG directive. This way in dev you can use Chrome's address bar to test your api and get json by defaut and you will still offer support XML in your prod environment.

@NickG 2013-04-09 18:24:00

Is it me, or is the first sentence incorrect? The code appears to totally remove XML, not simply change the default.

@Cohen 2013-07-03 10:09:07

@NickG: yes and no, it removes application/xml support but you can still use text/xml. (Although text/xml is considered deprecated)

@Cohen 2013-07-03 10:10:27

@NickG: a solution that is overlooked here and IMHO is a much better option (keeping application/xml) is the solution proposed by Felipe Leusin lower on this page. Using config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

@Kyle 2013-09-03 01:40:55

So, how do we do it via web config so we get json by default and XML if requested?

@Ken Smith 2013-09-09 13:20:28

@Felipse Leusin's answer below is actually shorter and works better.

@Adam Cox 2017-04-03 15:58:37

Also, this didn't work for me, so I ended up doing this.

@Aaron Daniels 2012-03-24 04:24:47

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.

@Spongman 2013-03-05 19:19:17

"so I can view it in the browser"

@Ivaylo Slavov 2014-04-25 21:37:16

@Spongman, yes you can. But use an extension like REST Client - most browsers have one like it. The direct typing of url in a browser is 1. Too limiting (no control over headers, cannot post data and etc); 2. Incorrect - The browser does not consume the web api as it is intended to be consumed - you cannot rely on it testing it properly. So, again, a good REST client add-on would fix that.

@suhair 2012-03-27 05:08:37

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.

@nuzzolilo 2012-04-13 23:28:29

This was very useful. You can also use UriPathExtensionMapping instead of QueryStringMapping if you want to use path.to/item.json

Related Questions

Sponsored Content

4 Answered Questions

[SOLVED] How to get POSTed JSON in Flask?

9 Answered Questions

31 Answered Questions

34 Answered Questions

[SOLVED] What is the correct JSON content type?

11 Answered Questions

10 Answered Questions

5 Answered Questions

[SOLVED] ServiceStack vs ASP.Net Web API

9 Answered Questions

[SOLVED] How to force ASP.NET Web API to always return JSON?

11 Answered Questions

[SOLVED] Fetch: POST json data

6 Answered Questions

[SOLVED] Using WebAPI or MVC to return JSON in ASP.NET

Sponsored Content