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.
1: public class XmlOutputAttribute : ActionFilterAttribute
3: public override void OnActionExecuted(
4: HttpActionExecutedContext actionExecutedContext)
6: ObjectContent content =
7: actionExecutedContext.Response.Content as ObjectContent;
9: var value = content.Value;
10: Type targetType = actionExecutedContext.Response.Content.
13: var httpResponseMessage = new HttpResponseMessage
15: StatusCode = HttpStatusCode.OK,
16: RequestMessage = actionExecutedContext.Request,
17: Content = new ObjectContent(targetType,
19: new XmlMediaTypeFormatter(),
23: actionExecutedContext.Response = httpResponseMessage;
How it works
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.