Skip to content

Instantly share code, notes, and snippets.

@lanwin
Created June 18, 2012 13:30
Show Gist options
  • Save lanwin/2948383 to your computer and use it in GitHub Desktop.
Save lanwin/2948383 to your computer and use it in GitHub Desktop.
ASP.Net WebApi: Answer text/html requests with application/json
public class JsonWithHtmlMediaTypeFormatter : JsonMediaTypeFormatter
{
public JsonWithHtmlMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, string mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
if(headers.ContentType.MediaType == "text/html")
headers.ContentType = new MediaTypeHeaderValue("application/json");
}
}
@lanwin
Copy link
Author

lanwin commented Jun 18, 2012

For debugging I want to let ASP.Net WebAPI answer with requests to text/html with application/json.

If I only add "SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));" it will work, but it sends the json as text/html to the browser, which dose not trigger tools like JsonView.

I can not use MediaTypeMappings since I want to allow custom formatters to return text/html if they are in a higher order.

Is there a better way of doing this?

@AlexZeitler
Copy link

You could rewrite the Header using a DelegatingHandler which evaluates whether you have a debug or release config active.
Or you could conditionally (based on active build config) add that Handler in your config.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment