关于调用Web API时出现的错误“The underlying connection was closed: An unexpected error occurred on a send”

发布时间 2023-08-01 17:13:14作者: 老飞飞

客户需求,要求调用他们的API来添加,查找,删除数据。
前些时候写了一个测试程序,调用API是OK的,但是今天突然就出现了"The underlying connection was closed: An unexpected error occurred on a send."的错误。当时的第一反应是账号信息过期了,因为是为了测试注册的临时账户,所以都是用的临时的信息。后来访问网站,发现还是可以访问的。所以账号过期就排除了。
然后查看资料,别人的解决方案有几种:

1. 可能是TimeOut的时间太短了,将TimeOut时间设置长一点。于是添加了下面的代码

request.Timeout = 36000;

2. 可能是ProtocalVersion不正确,于是添加了下面的代码

request.ProtocolVersion = HttpVersion.Version11;

3.设置KeepAlive为false,好吧,其实我不是很清楚这个KeepAlive的作用,只知道这是关闭"持久连接"。于是添加了代码:

request.KeepAlive = false;

但是上面的三种方式并不能解决我的问题。然后具体分析Error的Exception,发现错误中还提示了"Unable to read data from the transport connection:  An existing connection was forcibly closed by the remote host." 于是再次查找,最后发现原来客户的API将安全传输协议升级到TLS1.2了,于是添加下面的代码,就解决了这个问题。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

 

转载者话:  我的问题更奇怪,发生在操作系统从 windows 2012更新为windows 2022的时候。(另外一台2016正常运行).

当然程序员不同意这个是程序问题,而且报错的信息没有作者的信息那么详细.

The underlying connection was closed: An unexpected error occurred on a receive.Errors Location:   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()

最后抱着死马当做活马医的方式加上那句代码,结果是好的。

 

 

 

原文地址如下:

https://blog.csdn.net/nanbaifeiliao/article/details/80883252?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-5-80883252-blog-51554306.235%5Ev38%5Epc_relevant_anti_vip_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-5-80883252-blog-51554306.235%5Ev38%5Epc_relevant_anti_vip_base&utm_relevant_index=6