Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force ASP.NET Web API to always return JSON?

ASP.NET Web API does content negotiation by default - will return XML or JSON or other type based on the Accept header. I don't need / want this, is there a way (like an attribute or something) to tell Web API to always return JSON?

like image 917
Borek Bernard Avatar asked Sep 27 '12 19:09

Borek Bernard


People also ask

Is API response always JSON?

Not always. API's are methods of communicating between softwares. An APIs that return JSON objects is RESTful API which is type of Web API. There are a lot of APIs for example Microsoft Windows API, HTML5 Web APIs e.t.c With respect to JSON, some APIs return XML (mostly SOAP architecture).


2 Answers

Clear all formatters and add Json formatter back.

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

EDIT

I added it to Global.asax inside Application_Start().

like image 84
Filip W Avatar answered Sep 19 '22 06:09

Filip W


Supporting only JSON in ASP.NET Web API – THE RIGHT WAY

Replace IContentNegotiator with JsonContentNegotiator:

var jsonFormatter = new JsonMediaTypeFormatter(); //optional: set serializer settings here config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); 

JsonContentNegotiator implementation:

public class JsonContentNegotiator : IContentNegotiator {     private readonly JsonMediaTypeFormatter _jsonFormatter;      public JsonContentNegotiator(JsonMediaTypeFormatter formatter)      {         _jsonFormatter = formatter;         }      public ContentNegotiationResult Negotiate(             Type type,              HttpRequestMessage request,              IEnumerable<MediaTypeFormatter> formatters)     {         return new ContentNegotiationResult(             _jsonFormatter,              new MediaTypeHeaderValue("application/json"));     } } 
like image 24
Dmitry Pavlov Avatar answered Sep 20 '22 06:09

Dmitry Pavlov