title: Copying Http Request InputStream
body: <p>I'm implementing a proxy action method that forwards the incoming web request and forwards it to another web page, adding a few headers. The action method works file for GET requests, but I'm still struggling with forwarding the incoming POST request. </p>
  
  <p>The problem is that I don't know how to properly write the request body to the outgoing HTTP request stream. </p>
  
  <p>Here's a shortened version of what I've got so far:</p>
  
  <pre><code>//the incoming request stream
  var requestStream=HttpContext.Current.Request.InputStream;
  //the outgoing web request
  var webRequest = (HttpWebRequest)WebRequest.Create(url);
  ...
  
  //copy incoming request body to outgoing request
  if (requestStream != null &amp;&amp; requestStream.Length&gt;0)
              {
                  long length = requestStream.Length;
                  webRequest.ContentLength = length;
                  requestStream.CopyTo(webRequest.GetRequestStream())                    
              }
  
  //THE NEXT LINE THROWS A ProtocolViolationException
   using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                  {
                      ...
                  }
  </code></pre>
  
  <p>As soon as I call GetResponse on the outgoing http request, I get the following exception:</p>
  
  <pre><code>ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
  </code></pre>
  
  <p>I don't understand why this is happening, since requestStream.CopyTo should have taken care of writing the right amount of bytes. </p>
  
  <p>Any suggestions would be greatly appreciated. </p>
  
  <p>Thanks,</p>
  
  <p>Adrian</p>