views:

63

answers:

2

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);
A: 

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.

If this doesnt work, create a system.net trace log and see what is going on.

feroze
thanks for the info, the server is asp.net mvc2
AWC
A: 

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.

AnthonyWJones
good point, but I don't think it will be outside the basic ASCII range, will let you know the outcome...
AWC
corrected the bug and it is still happening, interestingly it works in FF (ver 2.6.10) but it still fails to send the request body in IE7.
AWC