Search code examples
c#soapstreamhttpwebrequestxmldocument

Either ContentLength must be set to a non-negative number, or SendChunked set to true in order to perform the write operation


Using HttpWebRequest, I used the following code to request a soap and get a stream:

XmlDocument soapEnvelopeXml = new XmlDocument();
HttpWebRequest webRequest = ...

using (Stream stream = webRequest.GetRequestStream())
{
    soapEnvelopeXml.Save(stream);
}

While this is the error message:

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.

As the above message says, I can't write to the stream because if I call the save soapEvelopeXml the application ends.


Solution

  • To resolve the error, simply enable a parameter within the HttpWebRequest object.

    webRequest.AllowWriteStreamBuffering = true;
    

    The parameter is part of the object properties and citing from the documentation on learn.microsoft.com

    AllowWriteStreamBuffering : Gets or sets a value that indicates whether to buffer the data sent to the Internet resource