HttpWebRequest调用GetResponse()后中止

本文关键字:调用 GetResponse HttpWebRequest | 更新日期: 2023-09-27 18:08:12

我遇到了一个让我抓狂的情况,而网上没有任何有用的真实信息。

我正在自动执行手动上传文件的过程。我3年前写的这段代码,它正常运行了一年,现在断断续续地出现故障。在查看我的请求的Fiddler流量和从浏览器发出的请求时,我看到的唯一区别是,在Fiddler中,在我的自动呼叫期间,我得到了这个带线的红色圆圈两次。

我的研究表明,这个图标意味着客户端中止了会话-我没有这样做。对于每个请求,我都传递相同的CookieContainer对象。我不知道为什么会发生这种情况,但如果我在Fiddler中查看日志行的属性,它会对我的自动请求说:

SESSION STATE: Aborted.
...
X-ABORTED-WHEN: SendingResponse
...
== TIMING INFO ============
ClientConnected:    16:25:58.563
ClientBeginRequest: 16:25:58.566
GotRequestHeaders:  16:25:58.567
ClientDoneRequest:  16:25:58.567
Determine Gateway:  0ms
DNS Lookup:         0ms
TCP/IP Connect: 0ms
HTTPS Handshake:    0ms
ServerConnected:    16:25:58.207
FiddlerBeginRequest:    16:25:58.567
ServerGotRequest:   16:25:58.567
ServerBeginResponse:    16:25:58.922
GotResponseHeaders: 16:25:58.922
ServerDoneResponse: 16:25:59.268
ClientBeginResponse:    16:25:59.268
ClientDoneResponse: 16:25:59.268

我从浏览器中得到的日志同一行看起来像这样:

SESSION STATE: Done.
...
ClientConnected:    10:33:09.347
ClientBeginRequest: 10:33:11.982
GotRequestHeaders:  10:33:11.982
ClientDoneRequest:  10:33:11.982
Determine Gateway:  0ms
DNS Lookup:         0ms
TCP/IP Connect: 0ms
HTTPS Handshake:    0ms
ServerConnected:    10:33:08.050
FiddlerBeginRequest:    10:33:11.982
ServerGotRequest:   10:33:11.982
ServerBeginResponse:    10:33:12.337
GotResponseHeaders: 10:33:12.337
ServerDoneResponse: 10:33:12.511
ClientBeginResponse:    10:33:12.511
ClientDoneResponse: 10:33:12.514

所以"完成"vs。"流产"。我从来没有在请求上调用Abort,我根本没有得到任何异常。以下是发生中止的代码:

using (WebResponse httpResponse = httpRequest.GetResponse())
{
    if (!httpResponse.ResponseUri.AbsoluteUri.Equals(string.Format("{0}main.htm", url), StringComparison.CurrentCultureIgnoreCase))
    {
        throw new Exception("Log in failed. Check the Username and Password information in the Setting table.");
    }
    httpResponse.Close();
}

我试着拿走"using"(尽管这是推荐的)和"Close"(也是推荐的),它仍然被中止。

我很感激

HttpWebRequest调用GetResponse()后中止

我遇到了这个问题,我意识到,如果响应流没有被读取(或访问),Fiddler中的请求报告它被中止了。对于我的用例,我不一定需要读取响应流,但我添加了一些代码来读取响应流(我没有缓冲或保存),然后Fiddler报告请求已完成。您上面的代码不能读取响应流,所以我将尝试一下。

        using (WebResponse httpResponse = httpRequest.GetResponse())
        {
            if (!httpResponse.ResponseUri.AbsoluteUri.Equals(string.Format("{0}main.htm", url), StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("Log in failed. Check the Username and Password information in the Setting table.");
            }
            var responseStream = httpResponse.GetResponseStream();
            if (null != responseStream)
            {
                var buffer = new byte[8192];
                while (responseStream.Read(buffer, 0, buffer.Length) > 0)
                {
                    // Do nothing here.
                }   
            }
            httpResponse.Close();
        }