title: HttpWebRequest unhandled "invalidcastexception" casting HttpWebResponse to System.Exception
body: <p>we have an application that makes calls to a remote web address using the HttpWebRequest class, which we get through the <code>WebRequest.Create</code> method.</p>
  <p>This is our actual code:</p>
  <pre><code>var request = (HttpWebRequest)WebRequest.Create(uri);
  request.Method = &quot;HEAD&quot;;
  request.Timeout = this.connectionTimeout;
  
  if (this.usePipelinedConnection)
  {
       request.KeepAlive = true;
       request.Pipelined = true;
  }
  
  request.BeginGetResponse(cb =&gt; logService.EndGetRequestStream(cb), null);
  </code></pre>
  <p>Now in a non-deterministic way (can't find a pattern to reproduce it) we get the following error:</p>
  <blockquote>
  <p>System.InvalidCastException</p>
  <p>Unable to cast object of type 'System.Net.HttpWebResponse' to type 'System.Exception'.</p>
  </blockquote>
  <p>with this stack trace:</p>
  <blockquote>
  <p>at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext&amp; context)</p>
  <p>at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)</p>
  <p>at System.Net.LazyAsyncResult.Complete(IntPtr userToken)</p>
  <p>at System.Net.ContextAwareResult.CaptureOrComplete(ExecutionContext&amp; cachedContext, Boolean returnContext)</p>
  <p>at System.Net.ContextAwareResult.FinishPostingAsyncOp()</p>
  <p>at System.Net.HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state)</p>
  </blockquote>
  <p>Documentation about this method reports several exceptions that can be thrown, but <code>InvalidCastException</code> is not one of those, meaning that it is unhandled in microsoft method.
  I started digging in .Net sources, and I think I found the culprit. In the HttpWebResponse.EndGetResponseStream method, there's this line:</p>
  <pre><code>throw (Exception) lazyAsyncResult.Result;
  </code></pre>
  <p>That's the only cast to Exception present in this method, so that must be it. Now the method is implemented in a way that it will reach this line only if the connectionstream is null, so the <code>lazyasyncresult.Result</code> property should contain an exception. In my case however, the branch is reached but <code>lazyasyncresult.Result</code> contains an <code>HttpWebResponse</code>, thus the boxing fails and I get that error. Now I have two considerations:</p>
  <ul>
  <li>If the content of <code>lazyasyncresult.Result</code> were correct, it would throw anyway (since the line starts with a throw) but it would be a meaningful error;</li>
  <li>Related to previous point, I think that if I have an HttpWebResponse the code branch that throws shouldnt be reached anyway</li>
  </ul>
  <p>Now my questions is plain simple: how do I prevent this from happening? I'm doing something wrong in my code or it's a plain bug in MS method?</p>
  <p>Here follows, for reference, the MS source of the method. I added some comments on the incriminated line.</p>
  <p>Thanks everyone for your time.</p>
  <pre><code>public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
      {
        if (Logging.On)
          Logging.Enter(Logging.Web, (object) this, &quot;EndGetRequestStream&quot;, &quot;&quot;);
        context = (TransportContext) null;
        if (asyncResult == null)
          throw new ArgumentNullException(&quot;asyncResult&quot;);
        LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;
        if (lazyAsyncResult == null || lazyAsyncResult.AsyncObject != this)
          throw new ArgumentException(SR.GetString(&quot;net_io_invalidasyncresult&quot;), &quot;asyncResult&quot;);
        if (lazyAsyncResult.EndCalled)
        {
          throw new InvalidOperationException(SR.GetString(&quot;net_io_invalidendcall&quot;, new object[1]
          {
            (object) &quot;EndGetRequestStream&quot;
          }));
        }
        else
        {
          ConnectStream connectStream = lazyAsyncResult.InternalWaitForCompletion() as ConnectStream;
          lazyAsyncResult.EndCalled = true;
          if (connectStream == null)
          {
            if (Logging.On)
              Logging.Exception(Logging.Web, (object) this, &quot;EndGetRequestStream&quot;, lazyAsyncResult.Result as Exception);
  
  // Here result contains HttpWebResponse so the cast to Exception fails. 
  // It would throw anyway (since there' a throw) but I think, since result contains a response
  // that the code shouldn't be hitting this if branch.
            throw (Exception) lazyAsyncResult.Result;
          }
          else
          {
            context = (TransportContext) new ConnectStreamContext(connectStream);
            if (Logging.On)
              Logging.Exit(Logging.Web, (object) this, &quot;EndGetRequestStream&quot;, (object) connectStream);
            return (Stream) connectStream;
          }
        }
      }
  </code></pre>