OK, I have not posted yet on the fact that WCF Web API is now reborn as ASP.NET Web API. I just did! Yes it is true. That in itself is very awesome news which I am sure many of you have already heard about. If not, go jump to Scott Gu’s blog here right now! I still have a post planned on that. Yes, I HAVE to post….later!
Moving on so that this idea doesn’t get lost in the warehouse of “to be posted” posts.
A common request people are asking is how to disable / remove the xml formatter so that their web apis ONLY return JSON regardless of the accept header.
There’s a few different common approaches to doing this, including:
- Create a custom message handler which overrides accept headers. I did one a long time ago here. The handler is then registered in the config.
- Remove the formatter from the collection. There’s a pretty easy way to do this as the formatters collection actually exposes an XmlFormatter property thus you can just remove it from the collection. Below is a snippet showing how to do this using the global config when hosted in ASP.NET.
var formatters = GlobalConfiguration.Configuration.Formatters;formatters.Remove(formatters.XmlFormatter);
This evening I was reading my friend Shawn Wildermuth’s blog post “WebAPI for the MVC guy” (which you should also check out) and I saw he was using a significantly more complex variant of the second option by looping through the formatters to remove the XmlFormatter. I am sure he would not have done that had he known about the formatter hanging off of the formatters collection, however it’s probably not the most obvious.
Looking at the code I then realized there’s a third. It’s by far the least amount of code of any of the approaches I’ve seen and it’s so dead simpleGlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
What this does is remove the supported media types from the XmlFormatter. Our content negotiation algorithm looks at that collection to determine if that formatter is a match. By making it empty, well it becomes no-op.