开发者

Silverlight HttpWebRequest content length empty, WTF?

When I run the following code the RESTful web service receiving the request has an empty body (content length = 0) and I don't know why?

If I run Fiddler whilst debugging the request executes as expected and the server receives the body, I guess I'm not configuing something for the request any ideas?

        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.ContentType = "text/xml";
        request.Method = "POST";
        request.CookieContainer = new CookieContainer();
        request.CookieContainer.Add(uri, new Cookie("SSOToken", HttpUtility.UrlEncode(SsoToken)));
        request.ContentLength = data.Length;

        request.BeginGetRequestStream(ar1 =>
        {
            var byteArray = Encoding.UTF8.GetBytes(data);

            var stream = request.EndGetRequestStream(ar1);
            stream.Write(byteArray, 0, data.Length);
            stream.Close();

            request.BeginGetResponse(ar2 => HandleSearchCompleted(ar2, request, action), state);
        },开发者_开发知识库 state);


First thing to do would be to fix the bug in the code. The code assumes the total number of bytes to be sent will be the number of characters in the data string. This isn't true if the string contains characters outside the basic ASCII character set.

You should first acquire the UTF8 byte array and use the length of this array as ContentLength and make sure you send the whole array.


You might try setting the content type to 'application/x-www-form-urlencoded' instead of 'text/xml', URL-encoding the xml content, and assigning it to a variable in the request body. I experienced this same behavior while trying to use Request.Form on the server side to access the data, until I set the content type correctly. If you're using some other method on the server to get the raw data, then this may not apply.


What kind of server is it? If the client is using HTTP/1.1 protocol (which is what it uses by default) then it wont post the entire entity body with the request. Instead it first just sends the headers, with an Expect: 100-continue header...

POST /url HTTP/1.1

Host: hostname

Content-Length: 128

Expect: 100-continue

At this point, if the server is ready to accept the data, it should reply with:

HTTP/1.1 100 Continue

So, it could be that you are posting to a buggy server that is not understanding the request correctly. That is why, when you post through Fiddler, the server ends up getting the entity because fiddler is probably sending the request headers and entity body to the server (after doing the HTTP/1.1 100 continue handshake with the client).

Workarounds?

  1. Try setting Expect100Continue=false on the HttpWebRequest.
  2. Try using HTTP/1.0 protocol.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜