How to change WebApi Content Negotation with a simple attribute

Today I was working on integrating with some third party software. I needed to create a web service that should return some XML to the third party application.

Content Negotation is a really nice feature in WebAPI. If you request JSON, you get JSON. If you request XML, you will get XML. The only problem was that they where specifying an incorrect header in the request. Because of this WebApi didn’t return XML and the third party application threw an exception.

Filing a bug would take to long so I started checking if I could somehow force the output of my WebApi to XML. After digging trough the WebApi source code (http://aspnetwebstack.codeplex.com/) I build a working solution that only requires you to use a single attribute.

XmlOutputAttribute

The following attribute can be applied to an Action Method. It will then force the output to XML.

 
   1:  public class XmlOutputAttribute : ActionFilterAttribute
   2:  {
   3:      public override void OnActionExecuted(
   4:                     HttpActionExecutedContext actionExecutedContext)
   5:      {
   6:          ObjectContent content = 
   7:                actionExecutedContext.Response.Content as ObjectContent;
   8:   
   9:          var value = content.Value;
  10:          Type targetType = actionExecutedContext.Response.Content.
  11:                          GetType().GetGenericArguments()[0];
  12:          
  13:          var httpResponseMessage = new HttpResponseMessage
  14:          {
  15:              StatusCode = HttpStatusCode.OK,
  16:              RequestMessage = actionExecutedContext.Request,
  17:              Content = new ObjectContent(targetType, 
  18:                                          value, 
  19:                                          new XmlMediaTypeFormatter(), 
  20:                                          (string)null)
  21:          };
  22:   
  23:          actionExecutedContext.Response = httpResponseMessage;
  24:   
  25:          base.OnActionExecuted(actionExecutedContext);
  26:      }
  27:  }

How it works

The HttpActionExecutedContext has a Response property that contains all data WebAPI uses to create a Response for the client.
A HttpResponseMessage has three properties that are important to us:
  • StatusCode
  • RequestMessage
  • Content
When creating the new XML HttpResponseMessage I give it a default status code of OK and reuse the Request from the HttpActionExecutedContext.
The Content is the property we want to change. We need to create a new ObjectContent and use that in the HttpResponseMessage.
The constructor looks like this:
   1:  public ObjectContent(Type type, object value, MediaTypeFormatter formatter, string mediaType);

We can get the type of the return data from the original Response.ObjectContent<T>. For the formatter we use the XmlMediaTypeFormatter and a null for mediaType.

That’s it! Then we have our new ResponseMessage and we can set it as the new value on our HttpActionExecutedContext.
ASP.NET MVC and ASP.NET WebApi both have a really great design. It’s easy to extend and you can do almost anything you can imagine.
I’m not sure this is the best way to do it but it works! If you have a better solution to this problem or if you have you created similar code then please leave a comment!

Wouter de Kort works as a lead architect and consultant. He helps organizations stay on the cutting edge of software development. Wouter focuses on DevOps. He loves solving complex problems and helping other developers to grow. Wouter authored the book DevOps on the Microsoft stack and a couple of other books. Wouter is a Microsoft MVP and an ALM Ranger. You can find him on Twitter (@wouterdekort), on his blog at wouterdekort.com and at the various conferences where Wouter speaks.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.