草庐IT

c# - System.Net.ProtocolViolationException : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse

coder 2024-05-23 原文

我得到了

"System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse" error when calling to the "BeginGetResponse" method of the web request.

这是我的代码:

try
{
    Stream dataStream = null;
    WebRequest Webrequest;
    Webrequest = WebRequest.Create(this.EndPointAddress);
    Webrequest.Credentials = new NetworkCredential(this.username, this.password);

    Webrequest.ContentType = "text/xml";
    Webrequest.Method = WebRequestMethods.Http.Post;                    

    byteArray = System.Text.Encoding.UTF8.GetBytes(xmlRequest.Children[0].InnerXML);

    Webrequest.ContentLength = byteArray.Length;

    dataStream = Webrequest.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);                

    RequestState rs = new RequestState();
    rs.Request = Webrequest;                    

    IAsyncResult r = (IAsyncResult)Webrequest.BeginGetResponse(new AsyncCallback(RespCallback), rs);
}
catch (Exception exc)
{                    
    TRACE.EXCEPTION(exc);
}
finally
{
    dataStream.Close();
}

更具体地说,在调用函数“getRequestStream()”后,Stream 抛出此异常的时间如下:

'stream.Length' threw an exception of type 'System.NotSupportedException'

可能是什么原因造成的?

最佳答案

这最终通过使用:

using (dataStream = Webrequest.GetRequestStream())
{
   dataStream.Write(byteArray, 0, byteArray.Length);
}

代替:

dataStream = Webrequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length); 

关于c# - System.Net.ProtocolViolationException : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31297612/

有关c# - System.Net.ProtocolViolationException : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse的更多相关文章

随机推荐