Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web api should return JSon by default [duplicate]

This is what I have currently

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

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

it works fine when I call API with query like this

for xml : http://localhost:49533/api/?type=xml
for json: http://localhost:49533/api/?type=json

but what I want is JSON by default? is that possible? I want above options available as well

like image 724
user570715 Avatar asked Apr 17 '26 01:04

user570715


1 Answers

Content negotiation looks at several things in your request including the Accept header (but also the contenttype header to infer returned results). If your request has XML in the accept header then it will go to XML.

Below is the chrome default headers, note that it's asking for XML, hence Web API will return XML by default for chrome.

{Connection: keep-alive Accept: text/html, application/xhtml+xml, application/xml; q=0.9, image/webp, /; q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US, en; q=0.8 Host: localhost:63586 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36 }

You can choose in your application to ignore the accept headers, by removing them from the formatters:

config.Formatters.JsonFormatter.MediaTypeMappings.Clear();

Then add your query mapping (similarly of course for the XML formatter).

like image 67
Yishai Galatzer Avatar answered Apr 19 '26 23:04

Yishai Galatzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!