Cleanest way to model bind Accept header in .NET MVC

Viewed 3528

I'm implementing a REST layer in .NET MVC 3. I'm looking for a clean way to grab the Accept header to determine if I should return Json or Xml.

I would also like to be able to spoof this header with a GET parameter for debugging (I want this to persist to prod too).

Here's how I'm currently detecting this:

if (Request.AcceptTypes.Contains("application/json") || Request.Url.Query.Contains("application/json"))

This is the only place in my controller code that touches the Request object directly. I would like a cleaner, more testable way to read this. My ideal solution would be a parameter on the controller.

I tried several keywords to see if the default model binder would pick up on it, but nothing I tried worked.

So what's the cleanest way to get this information? A custom model binder? Can you provide an example?

2 Answers
Related