Showing posts with label WebRequest. Show all posts
Showing posts with label WebRequest. Show all posts

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);
   }
}