ASP.NET Web API: Customizing the JSON representation for every request.
Returning JSON in response to a web request is what we all love to do, right? Except of course there's a serious security problem in returning arrays in JSON. So serious, that the ASP.NET MVC team decided to add a 'feature' that requires you to write in your explicit content that you're return JSON for a GET request.
Phil Haack called in JSON hijacking in his blog post. The obvious work around is to wrap your array in an object. Cool!
Now I want to do this in ASP.NET MVC Web API. Except of course, I don't want to change my model for this (there's nothing wrong with returning XML, well nothing to do with this security threat anyways) so what I was looking for was a way to customize the way JSON was created.
The solution is to create a class that inherits from JsonMediaTypeFormatter, which is the class responsible to support the JSON media type. I'm calling it MyJsonMediaTypeFormatterbecause it's .. mine.
as you can see, I'm only overriding one method, and I'm not doing too much either. Simply wrapping the value in an anonymous object and letting the base class do all the heavy lifting.
Now onto configuration. I simply add the following lines to my Application startup:
And presto, every JSON response that is handled through ASP.NET Web API is wrapped in an object!
Questions?
Written on August 22, 2012