4

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

4
  • it should've returned Json by default.. Commented Feb 27, 2014 at 4:22
  • its returning xml by default Commented Feb 27, 2014 at 14:33
  • When I request like this - localhost:49533/api/Product I get XML Commented Feb 27, 2014 at 15:03
  • 1
    how you checked, using browser? was it chrome? see OP's comment here : stackoverflow.com/questions/18266952/… Commented Feb 28, 2014 at 0:49

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.