title: Received "Request was cancelled" error when writing JSON data to HttpWebRequest
body: <p>I've a iOS application written in C# using Monodevelop, and as part of the application I make a call to a web service. The web service call requires that JSON data to be written to the request. However, I receive an error the first time I attempt to write the data; all subsequent calls to the same method with the same parameters work. The following is a snippet of the relavent code:</p>
  
  <pre class="lang-csh prettyprint-override"><code>// Start snippet
  
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (_connectionSettings.Uri);
  request.Timeout = 15000; // milliseconds
  if (_connectionSettings.Username != "") {
      request.Credentials = new NetworkCredential (_connectionSettings.Username, _connectionSettings.Password);
  }
  
  if (post) {
      request.Method = "POST";
      request.ContentType = "application/json";
      if (jsonData != null) {
          byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsonData);
          request.ContentLength = byteArray.Length;    
          using (Stream ds = request.GetRequestStream()) {  //&lt;--- ERROR HERE
              ds.Write (byteArray, 0, byteArray.Length);
          }
      } else {
          request.Method = "GET";
  }
  
  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
  
  // end snippet
  </code></pre>
  
  <p>The error I get is as follows:</p>
  
  <blockquote>
    <p>System.Net.WebException: Request was cancelled. ---> 
    System.Exception:
    Cannot close the stream until all bytes are written
    --- End of inner exception stack trace ---   at</p>
    
    <p>System.Net.WebConnectionStream.Close ()
    [0x00121] in</p>
    
    <p>/Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:785
    at System.IO.Stream.Dispose () [0x00000] in</p>
    
    <p>/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.IO/Stream.cs:93
    at</p>
    
    <p>MyCustomMethod (System.String&amp; responseString, System.String jsonData, Boolean post,
    Boolean suppressAlert) [0x00101] in /Path/To/My/Class.cs:192</p>
  </blockquote>
  
  <p>Any ideas what I could be doing wrong?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p><strong>Ok, apparently when stepping through the application, the method works every time. What I've noticed is that when the error is throw, the request.ContentLength is zero despite the fact that the byteArray.Length is non-zero. However when stepping through the application, the request.ContentLength keeps the expected value of the byteArray.Length.</strong></p>