HttpWebRequest:基础连接已关闭异常:The underlying connection was closed。

今天理IIS上Asp.net程序的所有报错日志,发现好报The underlying connection was closed: Unable to connect to the remote server. 于是搜了下,发现很多人遇到这个异常,可是却没有标准的解决方案,一般有一下几种。
 
1.如果用了代理,设置正确。
2.如果用了firewall,将firewall禁掉试试。
3.将Lan设置中的Automatically Detect Settings禁掉。
4.重装.Net Framework。
5.如果用了抓取,可以将HttpWebRequest的KeepAlive属性设置为false,HttpWebRequest的KeepAlive属性默认是true
对应我线上的程序,1、2、3、4都可以排除,我的就是抓取时报这个错,采用了第5种方法后,异常消失了。

===================

服务端问题:

服务器会拒绝访问的,不能别人不是可以一直攻击服务器了,这样导致连接失败是正常的, 你可以把返回的数据保存起来

服务器端的问题。检查它有没有缺少 FlushClose语句并且确实执行到这里。有时候甚至是服务器端抛出了异常(可惜有些程序员写的程序隐藏了异常,使得无法调试)。


==================================================
参考解决方案1:

 write a bit about how Fiddler can "magically" fix things here: http://blogs.telerik.com/fiddler/posts/13-02-28/help!-running-fiddler-fixes-my-app-

The issue you're encountering is actually a bug in the .NET Framework itself. The rules of HTTP are such that the server may close a KeepAlive connection at any time after sending the first response (e.g. it doesn't need to accept another request on the connection, even if the client requested KeepAlive behavior).

.NET has a bug where it expects that the server will include a Connection: close response header if it will close the connection after the response is complete. If the server closes the connection without the Connection: Close header (entirely valid per RFC2616), .NET will encounter the closed connection when attempting to send the next request on the connection and it will throw this exception. What .NET should be doing is silently creating a new connection and resending the request on that new connection.

Fiddler resolves this problem because it doesn't care if the server closes the connection, and it keeps the connection to the client alive. When the client sends its second request, Fiddler attempts to reuse its connection to the server, notices that it's closed, and silently creates a new connection.

You can mitigate this problem in your code by:

  1. Disabling keepalive on the request (this hurts performance)
  2. Catching the exception and retrying automatically
  3. Changing the server to keep connections alive longer

Approach #3 only works if you control the server and because the client may be behind a gateway/proxy that closes connections after use, you should probably use approach #2 as well.

解决方案2:

Fiddler works as an Internet Proxy. If your code works while Fiddler is running, (and maybe also from a browser), then you may have a problem with your proxy settings.


如果使用Fiddler工具后,程序能够工作,可能是IE的代理设置错了,因为FILDER是工作在代理模式下。

解决方案3:

在我的例子中,这解决了这个问题:

System.Net.ServicePointManager。Expect100Continue = false;

和以上。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值