logo

Premium Support
24/7/365

Premium support customers may submit help-desk tickets using the form below.
Alternatively, the help-desk system can be accessed directly at support.maxiomtech.com. support@maxiomtech.com
info@maxiomtech.com
+1 (703) 942-9420
 

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.

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

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.

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

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]
Jonathan Sheely

Sr Software Engineer at InspectorIT. Jonathan is an out of the box thinker who has over 10 years experience building and supporting web application software and infrastructure. Jon specializes in ASP.NET C#, Javascript and CSS but is willing to learn anything that gets the job done.

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

    Your Data Expose module is pretty slick.