Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default Web API 2 to JSON formatter?

I have a Web API project that returns some product data. It negotiates the return type correctly depending on the Accept header (JSON/XML) of the request. The problem is, if no Accept header is specified it returns XML, but I want it to return JSON by default

http://website.com/MyPage?type=json // returns json
http://website.com/MyPage?type=xml // returns xml
http://website.com/MyPage // returns xml by default

Here is my current code looks like:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
like image 664
Nick Kahn Avatar asked Aug 10 '14 01:08

Nick Kahn


People also ask

What is the default formatter in Web API?

Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.

How do I use media type formatter in Web API?

The media type determines how Web API serializes and deserializes the HTTP message body. Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter. To create a media formatter, derive from one of these classes: MediaTypeFormatter.

Which property returns all the formatter in Web API?

Configuration. Formatters returns MediaTypeFormatterCollection that includes all the formatter classes. The above example returns names of all the formatter classes as shown below.


2 Answers

Add this in your App_Start/WebApiConfig.cs:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
like image 105
Triet Doan Avatar answered Oct 19 '22 19:10

Triet Doan


I think Web API just uses the first formatter it can find in the Formatters collection. You can change the ordering with something like

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

But it seems the JSON formatter should be the first one by default so you might want to check if you're already modifying this collection somewhere.

like image 28
Victor Efimov Avatar answered Oct 19 '22 21:10

Victor Efimov