17

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?

user3815821
  • 397
  • 2
  • 3
  • 12
  • Please don't add "searched alot" and "thank you" to your post. To show effort - post code (ok as it is in current post) and links to solutions you've tried along with short sentence who it did not solve your problem. – Alexei Levenkov Jul 08 '15 at 15:53
  • possible duplicate of [System.Net.ProtocolViolationException Exception C# Post and Getresponse](http://stackoverflow.com/questions/18192423/system-net-protocolviolationexception-exception-c-sharp-post-and-getresponse) – Orel Eraki Jul 08 '15 at 16:01
  • That question explains a different error than this one, so it is not duplicated. – user3815821 Jul 08 '15 at 16:07

3 Answers3

18

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); 
user3815821
  • 397
  • 2
  • 3
  • 12
4

Your code should work for .NET 2.0 From 4.0 and up you should close the stream after writing:

dataStream = Webrequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
HMartyrossian
  • 137
  • 2
  • 7
1

Check to verify that your server is set up to accept large files. You may find that you are running into the 4 meg default limit.

Add the following to your web.config file for larger file uploading:

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="104857600" />
        </requestFiltering>
    </security>
</system.webServer>