Web API, JSON by Default in Web Browsers

I use a few methods for examining and debugging JSON output. One of those is to view it in a browser. If that browser is Internet Explorer, then the file just gets opened automatically in Notepad++ (which, nicely, will also just keep updating an existing file, avoiding tab clutter). There, I use the JSON Viewer plugin, which is decent enough, if a bit unpolished. If the browser is Chrome, I use JSONView. One advantage is that if the JSON doesn’t end up formatted, you know right away it isn’t valid. But, unlike JSONLint it can’t tell you where the problem is.

For whatever inane reason (XML is dead, right? :-)) Chrome likes to tell servers that it accepts XML. So your “purist” Web API that is set up to deliver only JSON gets this request and fails to serialize into XML. So Chrome just gets a big, nasty error message back.

Fortunately, there is way to head this off at the pass. In the Web API global.asax.cs file you can remove the XML formatter (if you’re never going to use it):

using System;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace GeoDataAPI
    public class Global : HttpApplication
        protected void Application_Start(object sender, EventArgs e)

            // Ignores browsers like Chrome requesting xml.
            var config = GlobalConfiguration.Configuration;
            var appXmlType =
                config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");

Another approach is to use

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

But I found this caused a problem with third-party data that contained HTML break tags. The JSON was sent out with carriage returns, which caused it to be invalid. If you don’t need XML, I recommend the other way of doing this.