Friday, January 29, 2010

CF HttpWebRequest does not allow writing to the request stream by default

While trying to send data via a request stream, I ran into this error in the compact framework:
ex = {"Either ContentLength must be set to a non-negative number, or SendChunked set to true in order to perform the write operation when AllowWriteStreamBuffering is disabled."}

This was a bit confusing since I didn't get this error when running from a windows client.  I finally figured out that I have to allow writing to the stream:

private void SendData(WebRequest request, object dto)
{
   // I had to add this for the CF framework. It isn't true by default.
   if (request is HttpWebRequest)
      ((HttpWebRequest) request).AllowWriteStreamBuffering = true;

   using (Stream requestStream = request.GetRequestStream())
   {
         if (IsJsonRequest(request))
            SendDataAsJson(requestStream, dto);
        else SendDataAsXml(requestStream, dto);
   }
}

2 comments:

JoBlogs said...

Hello Dave,

Thanks so much for this, I spent a good 6Hrs trying to figure out why my HttpWebRequest was not working.

Ian said...

8 years on & 4 years since the last comment, thanks once again - you've just saved me hours of work. Just goes to show a good blog entry never gets old :)