Is there an ASP.NET MVC controller or helper class that can automatically return the proper HTTP response based on the HTTP request header? I'd like it to be able to return JSON, XML, or a View based on the request's content type, with the only thing I have to do is populate some global Model
object with data from the database.
views:
141answers:
2
+3
A:
Check out this article - you can do it using action filters:
The following is a filter which makes the whole thing much cleaner. The filter looks for Content-Type headers in the HTTP request. If it matches text/xml then Plain Old XML (POX) is returned and if it matches application/json the output is JSON.
James Kolpack
2009-12-16 03:09:19
Thanks, I've seen that article before, but I didn't really want to decorate all my methods with an attribute. However, it seems that it's the only way for now.
Daniel T.
2009-12-16 19:12:39
The attributes can also be applied to the controller - but that may not be helpful since you're probably needing action-specific granularity.
James Kolpack
2009-12-16 20:10:52
For now I want to use JSON/XML/View for every action, though I can see situations where you might not want it for everything, such as a login page or a report generator/viewer.
Daniel T.
2009-12-16 21:34:06
A:
Have a look at this article also, doesn't use filters and works great for me.
I use JSON responses in several places on my app, but if a users javascript is disabled it will fallback and render the standard view...it checks the response type to do this.
http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx
Paul
Paul Hinett
2009-12-20 04:06:03
Thanks, it looks like a good read. For our current project, we decided to split our controllers because the JSON API will be too different from the webpage views, but I still like the idea of having a unified controller that is 'generic' in that it doesn't care about what type the request is, but knows how to spit out the appropriate response.
Daniel T.
2009-12-20 10:32:55