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

前端 未结 4 1965
说谎
说谎 2021-01-14 09:34

This one is real simple, run this Silverlight4 example with the ContentType property commented out and you\'ll get back a response from from my service in xml. Now uncomment

4条回答
  •  伪装坚强ぢ
    2021-01-14 09:57

    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.

提交回复
热议问题