C# “HttpWebRequest未处理”;“无效卡斯特例外”;正在将HttpWebResponse强制转换为System.Exception

C# “HttpWebRequest未处理”;“无效卡斯特例外”;正在将HttpWebResponse强制转换为System.Exception,c#,exception,casting,httpwebrequest,C#,Exception,Casting,Httpwebrequest,我们有一个应用程序,它使用HttpWebRequest类调用远程web地址,我们通过WebRequest.Create方法获得该类 这是我们的实际代码: var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "HEAD"; request.Timeout = this.connectionTimeout; if (this.usePipelinedConnection) { r

我们有一个应用程序,它使用HttpWebRequest类调用远程web地址,我们通过
WebRequest.Create
方法获得该类

这是我们的实际代码:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "HEAD";
request.Timeout = this.connectionTimeout;

if (this.usePipelinedConnection)
{
     request.KeepAlive = true;
     request.Pipelined = true;
}

request.BeginGetResponse(cb => logService.EndGetRequestStream(cb), null);
现在,以一种非确定性的方式(无法找到模式来复制它),我们得到以下错误:

System.InvalidCastException

无法将“System.Net.HttpWebResponse”类型的对象强制转换为“System.Exception”类型

使用此堆栈跟踪:

位于System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult、TransportContext和context)

位于System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)

在System.Net.LazyAsyncResult.Complete(IntPtr userToken)中

在System.Net.ContextAwareResult.CaptureOrComplete(ExecutionContext&cachedContext,布尔返回上下文)

在System.Net.ContextawarerResult.FinishPostingAsyncOp()中

位于System.Net.HttpWebRequest.BeginGetResponse(异步回调,对象状态)

关于此方法的文档报告了几个可以抛出的异常,但
InvalidCastException
不是其中之一,这意味着它在microsoft方法中未被处理。 我开始挖掘.Net的资料,我想我找到了罪魁祸首。在HttpWebResponse.EndGetResponseStream方法中,有以下行:

throw (Exception) lazyAsyncResult.Result;
这是此方法中唯一存在的对异常的强制转换,所以必须是这样。现在,该方法的实现方式是,仅当connectionstream为null时,它才会到达此行,因此
lazyancresult.Result
属性应该包含一个异常。然而,在我的例子中,到达了分支,但是
lazyancresult.Result
包含一个
HttpWebResponse
,因此装箱失败,我得到了那个错误。现在我有两个考虑:

  • 如果
    lazyasyncresult.Result
    的内容正确,它无论如何都会抛出(因为该行以抛出开头),但这将是一个有意义的错误
  • 与前一点相关,我认为如果我有一个HttpWebResponse,抛出的代码分支无论如何都不应该到达
现在我的问题很简单:如何防止这种情况发生?我在我的代码中做了一些错误,或者这是MS方法中的一个普通错误

以下是该方法的MS来源,以供参考。我补充了一些关于有罪的评论

谢谢大家抽出时间

public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
    {
      if (Logging.On)
        Logging.Enter(Logging.Web, (object) this, "EndGetRequestStream", "");
      context = (TransportContext) null;
      if (asyncResult == null)
        throw new ArgumentNullException("asyncResult");
      LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;
      if (lazyAsyncResult == null || lazyAsyncResult.AsyncObject != this)
        throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
      if (lazyAsyncResult.EndCalled)
      {
        throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[1]
        {
          (object) "EndGetRequestStream"
        }));
      }
      else
      {
        ConnectStream connectStream = lazyAsyncResult.InternalWaitForCompletion() as ConnectStream;
        lazyAsyncResult.EndCalled = true;
        if (connectStream == null)
        {
          if (Logging.On)
            Logging.Exception(Logging.Web, (object) this, "EndGetRequestStream", 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, "EndGetRequestStream", (object) connectStream);
          return (Stream) connectStream;
        }
      }
    }

我从未使用过这个异步任务库,如果这是一个幼稚的问题,请原谅。但是您不是调用了错误的EndGetXXX函数吗

request.BeginGetResponse(cb=>logService.EndGetRequestStream(cb),null)


我不知道logService变量是什么,但它不应该调用EndGetResponse()吗?

找到这个错误的原因了吗?