views:

141

answers:

2

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.

+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
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.
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
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.
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
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.