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

客户需求,要求调用他们的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;



你可能感兴趣的:(C#)