How do I use HttpWebRequest GET method w/ ContentType="application/json" How do I use HttpWebRequest GET method w/ ContentType="application/json" json json

How do I use HttpWebRequest GET method w/ ContentType="application/json"


Stephen, setting the content type is to allow SENDING JSON, not receiving it. There are several ways to do this. You can support both JSON and XML or only JSON. If all you want to do is support JSON then you can do this by setting the ResponseFormat property on the WebGet attribute for the service operation.

If you want to support both JSON and XML then you need to either enable automatic format selection on the service and send an accept header of "application/json", otherwise you can use a format string parameter in the query string and have the service use the WebOperationContext.OutgoingResponse.Format property.

Here's a post that covers various ways to do this from the server side. If you go the route of supporting automatic format selection then you need to set the accept header of the HttpWebRequest to "application/json"


If you finally determine that it's a problem in the Silverlight HttpWebRequest, i.e., it might have a bug or excessively stupid security check in it that keeps it from handling text/json responses, one reasonable (if annoying) workaround might be to shell out to javascript to make the request, using the XMLHttpRequest object, and then return the results to Silverlight. Annoying, but possible.


Glenn Block's answer already seems to say this but I guess it was not clear enough.

The Content-Type header tells what type of data is in a POST body or HTTP response body

Your HTTP request is not either of these. It is a GET request without any body. This is why you are getting a protocol violation exception - GET requests cannot have a Content-Type header because by definition they do not have any content.

Your Fiddler request is working simply because WCF is very accomodating to buggy clients. The error is coming from inside the Silverlight networking stack, which refuses to send a broken request.

Let's take it from the top: you want to get back JSON data. This is accomplished using the Accept header, which tells the server what kind of data you want to get back. Therefore, replace this

wreq.ContentType = "application/json"; 

with this

wreq.Accept = "application/json"; 

and you will get JSON data from the server.