Wednesday, November 14, 2012

Asp.Net WebApi–allowing format to be specified in the URL

By default WebAPI looks at the header to determine how to serve back content. But what if you cant set the header in your client app and so you need to specify the format via the URL?

What you need to do is to add a query string mapping for the XML formatter. This can be done using the following code in “Application_Start” of the Global.aspx.cs file:

MediaTypeFormatter xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xmlFormatter.AddQueryStringMapping("format", "xml", "text/xml");

And what if you want XML to be your default formatter? The easy way I found for this was to reorder the formatters in “GlobalConfiguration.Configuration.Formatters”, so that the XML formatter was the first in the list.

MediaTypeFormatter xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
MediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

GlobalConfiguration.Configuration.Formatters.Insert(0, xmlFormatter);

Note: If you reorder the formatters, you will need to add a query string mapper for JSON:

jsonFormatter.AddQueryStringMapping("format", "json", "application/json");

No comments: