Handling Content Type as we should, through HTTP Headers
In the previous post I spiked a solution to return different result types depending on a requested format. While the solution I came up with was sufficient to address the points issued on a thread at .NetArchitects, Eric Hexter hit the nail on the head with the following tweet:
@pedroreys nice post on the formatter. I would consider http headers instead of routing, although that is hard to manually debug
The right way to specify the types which are accepted for the response is by using the Accept request-header. It’s been a while since Eric’s tweet, but here is the solution I came up with.
Lemme first define the expectations I defined:
If the Accept header of the request
Contains text/html a ViewResult should be returned.
Contains application/json and not contains text/html a JsonResult should be returned.
Contains text/xml and not contains text/html a XmlResult should be returned.
In order to be able to format the result based on the requested content-type on the HTTP header, I will create a base controller class that will provide this functionality to the controller. I will call it ContentTypeAwareController.
That’s it. The Client Controller now is able to respond to Json, Xml or Html requests. Let’s check it.
The web page is still being rendered as expected. Fine.
But now, let’s see what responses do I get when I change the Http Header to “application/json”:
Yeah, a Json result. Cool. What about “text/xml”:
Yeap, that works too. Finally, let’s see if the 406 status code is returned when an invalid content type is requested:
So, with not so much code the Client Controller now is able to format its result based on the Content Type requested on the HTTP Header, as it should have been before. Off course this is a spike and the code can be improved. Feel free to grab it from github and improve it.