Created
June 18, 2012 13:30
-
-
Save lanwin/2948383 to your computer and use it in GitHub Desktop.
ASP.Net WebApi: Answer text/html requests with application/json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
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
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?