ContentLength 必须设置为非负数,或者 SendChunked 设置为 true 才能执行写操作

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

使用 HttpWebRequest,我使用以下代码请求肥皂并获取流:

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

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

虽然这是错误消息:

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.

正如上面的消息所说,我无法写入流,因为如果我调用 save soapEvelopeXml,应用程序就会结束。

要解决该错误,只需在 HttpWebRequest 对象中启用一个参数。

webRequest.AllowWriteStreamBuffering = true;

该参数是对象属性的一部分,引用自 docs.microsoft.com

上的文档

AllowWriteStreamBuffering : 获取或设置一个值,该值指示是否缓冲发送到 Internet 资源的数据