HttpWebRequest在调用GetResponse()后中止

时间:2013-04-08 22:54:39

标签: c#

我有一种情况让我发疯,而且网上没有任何真实的信息有帮助。

我正在自动执行上传文件的手动过程。我实际上就像3年前写的这段代码,它在一年中顺利运行,现在它间歇性地失败了。在查看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

所以“完成”与“中止”。我从未在请求​​中打电话给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();
}

我试图取消“使用”(即使它是推荐的)和“关闭”(也推荐)并且它仍然会被中止。

我很感激

1 个答案:

答案 0 :(得分:2)

我遇到了这个问题,我意识到如果没有读取(或访问)响应流,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();
        }