how to force web api serializer using querystring

Topics: Web Api
May 20, 2012 at 1:54 PM

Hello,

I want to control the dataformat returned by my webapi using querystring but can not figure out how to do this.

What I want is

http://myhost.com/api/items?type=json

or

http://myhost.com/api/items?type=xml

No matter what I do, I get xml.

This should not be hard, what am I missing?

May 20, 2012 at 4:55 PM

Here's how you do it: You create a QueryStringMapping and register it with the formatters that you want to respond this way. On your HttpConfiguration object, do the following:

            QueryStringMapping xmlMapping = new QueryStringMapping("type""xml""application/xml");
            QueryStringMapping jsonMapping = new QueryStringMapping("type""json""application/json");
 
            config.Formatters.XmlFormatter.MediaTypeMappings.Add(xmlMapping);
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(jsonMapping);
Thanks,
Henrik
May 21, 2012 at 5:23 AM
Great!

Thank you!

How do I set up the json formatter as the default? (when no querystring is present)

Right now, it defaults to xml

Thanks,

Netanel


From: [email removed]
To: [email removed]
Date: Sun, 20 May 2012 08:55:59 -0700
Subject: Re: how to force web api serializer using querystring [wcf:356432]

From: HenrikN
Here's how you do it: You create a QueryStringMapping and register it with the formatters that you want to respond this way. On your HttpConfiguration object, do the following:
            QueryStringMapping xmlMapping = new QueryStringMapping("type", "xml", "application/xml");
            QueryStringMapping jsonMapping = new QueryStringMapping("type", "json", "application/json");
 
            config.Formatters.XmlFormatter.MediaTypeMappings.Add(xmlMapping);
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(jsonMapping);
Thanks,
Henrik
Read the full discussion online.
To add a post to this discussion, reply to this email (wcf@discussions.codeplex.com)
To start a new discussion for this project, email wcf@discussions.codeplex.com
You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on CodePlex.com.
Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at CodePlex.com
May 21, 2012 at 7:38 AM

I don't see that with the latest bits - I get JSON as the default format. If you are running the beta bits then it may be a bug -- we have added better support for wildcards and the like since then.