Change WebAPI Default Output Format

Change WebAPI Default Output Format

Change WebAPI Default Output Format

I recently built a module for DotNetNuke that utilizes the Microsoft WebAPI framework but ran into the situation that the main XML module I planned on using with was unable pass Content-Type to change the output from WebAPI’s default JSON serialization to XML.

In case you were wondering changing the default serialization does not effect WebAPI’s ability to render in alternative methods it simply changes how it reacts when you omit the Content-Type header.

Configuring Your Service Controller

Your service controller implementation will only require a few small modifications to allow for changing the default output. The first is to define what your default output is and how to access it.

[code lang=”csharp”]
string defaultOutput = "text/xml";
private string GetContentType
{
get
{
if(Request.Headers.Accept.ToString().Contains("json"))
{
return "text/json";
}
else
{
return defaultOutput;
}
}
}
[/code]

We are simply creating a variable and a property to get that value, nothing fancy. But note In my example I only care about XML and JSON which will be the only content types handled. However you could easily modify this property to return a dynamic content type if one is provided.

The last step is to utilize a MediaTypeHeaderValue class in your response. This will tell WebAPI which formatter to use in order to serialize the output.

[code lang=”csharp”]
[HttpGet]
public HttpResponseMessage Execute(int portalId)
{
return Request.CreateResponse(HttpStatusCode.OK, resultInfo, new MediaTypeHeaderValue(GetContentType));
}
[/code]

Now if you visit your service in a web browser you will get an XML response instead of JSON.

You can see an example of this being used in my Data Expose module for DotNetNuke

[button link=”https://github.com/jsheely/DotNetNuke-Data-Expose” style=”download” window=”yes”]Data Expose on GitHub[/button]

Antonio Chagoury

Hi, I'm Antonio, Founder and CEO of Maxiom Technology (formerly Inspector IT).I'm a technology executive and entrepreneur who has achieved consistent success in driving growth, generating revenue, and enhancing value in domestic and international markets through technology product innovations.

1 Comment
  • Frederick King
    Posted at 12:31 pm, March 13, 2013

    Your Data Expose module is pretty slick.