Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

I am getting the

"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.

This is my code:

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

More specifically, after calling to the function "getRequestStream()", the Stream is throwing this exception for the lenght:

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

What could be causing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This finally worked by using:

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

Instead of:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...