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?
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).
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()
.
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")); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With