How to configure WebAPI always return JSON

WebAPI will return JSON or XML based on the request accept header. But some times you may need to return JSON only, without considering the accept header.

Here is the code snippet which will helps to return JSON always.

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

You need to place this code in the WebApiConfig class, Register method.

The problem with this approach is, even though you are clearing all the formatters, the content negotiation process is still happening, which is a tiny overhead. You can avoid this by implementing your own ContentNegotiator by implementing IContentNegotiator interface.

Happy Programming.

No related content found.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>