Return JSON as default

Topics: Web Api
Sep 17, 2011 at 5:36 PM

How can I change the  QueryableSample from WCF Web API Preview 4 so it returns JSON as default (without having to set te accept header on the client)? Is it possible?

leo

 

Sep 17, 2011 at 9:34 PM

By default we pick application/json as the format is one of the following things apply to the request

1) If there is a request accept header field including application/json

2) If there is a request entity body of type application/json

3) If there is a X-Requested-With header field with a value of xmlhttprequest.

All AJAX libraries send the X-Requested-With header so if requested from AJAX then you will get json.

To support this we added a new RequestHeaderMediaTypeMapping which allows you to easily add mappings from any HTTP header field to a particular media type. Examples is the X-Requested-With but you could also imagine that you wanted to pick a format based on other header fields.

You can change the order of formatters using the HttpConfiguration object. If you look under Formatters you will find a collection that has the default formatters. The first entry in this collection is the default formatter which we pick if nothing else tells us to pick a better one.

Henrik

From: 0bscur3 [email removed]
Sent: Saturday, September 17, 2011 10:37 AM
To: Henrik Frystyk Nielsen
Subject: Return JSON as default [wcf:272939]

From: 0bscur3

How can I change the QueryableSample from WCF Web API Preview 4 so it returns JSON as default (without having to set te accept header on the client)? Is it possible?

leo

Coordinator
Sep 17, 2011 at 11:26 PM
This handler will do it.

http://codepaste.net/wehh49

plug it in via the MessageHandlers prop of config.

Sent from my Windows Phone

From: 0bscur3
Sent: 9/17/2011 10:36 AM
To: Glenn Block
Subject: Return JSON as default [wcf:272939]

From: 0bscur3

How can I change the QueryableSample from WCF Web API Preview 4 so it returns JSON as default (without having to set te accept header on the client)? Is it possible?

leo

Sep 18, 2011 at 12:34 AM

(sorry for my bad english)

Henrik, thanks for the explanation, now I understant better how this work... I need to consume the data from a php project (the request is made on the server). The host do not allow me to use cURL  to build a proper request and other alternatives that I tried didn't work... since I only need JSON and would only read small sets of data, to force the result to be JSON always (so I could just file_get_content it) resolves my problems :)

Thanks gblock, the ForceJsonHandler class worked perfectly.