Changing the WEB API content formatter using a query string parameter

Posted: June 2, 2012 in .NET, MVC, Uncategorized
Tags: ,

(using MVC4 beta)

In some cases it is not easy to alter the header values to negotiate the content type returned from WEBAPI.

There is a QueryStringMapper object you can add to the Media Type Formatter objects that allow you to use a query string to negotiate the content format.

In the example below,  I am adding a query string parameter ‘format’ to the mapping. When ‘format’ == ‘xml’, the content type is ‘text/xml’ and the XmlMediaTypeFormatter is used.

I run this in the ‘Application_Start’ method of the Global.asax 

            foreach (var item in GlobalConfiguration.Configuration.Formatters)
            {
                if (typeof(XmlMediaTypeFormatter) == item.GetType())
                {
                    item.AddQueryStringMapping("format", "xml", "text/xml");
                }
            }

Example api call – http://localhost/api/foo?format=xml

Advertisements
Comments
  1. Aurimas says:

    Good, exactly what I was searching for.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s