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

user3815821 picture user3815821 · Jul 8, 2015 · Viewed 20.2k times · Source

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?

Answer

user3815821 picture user3815821 · Jul 15, 2015

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