刹那的菜鸟

博客园 首页 新随笔 联系 管理

程序会间歇性访问某个https接口,一直用的好好的,今天突然报错了,异常就发生在访问接口的地方,曰“请求被中止,未能创建 SSL/TLS 安全通道。”,另外有台电脑也有跑该程序,也是同样的报错,看来是接口方改动过什么了。

搜索一番,原因应该是,接口方变更了安全协议,而客户端并未启用该协议。解决办法自然就是:让客户端启用该协议。具体就是在发起网络请求之前确保ServicePointManager.SecurityProtocol中含有服务端所用的安全协议,如果不知道或希望客户端健壮一点,当然最简单的方式就是把所有可用的协议都启用,随你服务端将来怎么换。代码如下:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
但如果客户端是基于.net framework 4.0,SecurityProtocolType枚举中并没有Tls11和Tls12,这就需要直接填值:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| (SecurityProtocolType)0x300 //Tls11
| (SecurityProtocolType)0xC00; //Tls12

posted on 2020-07-13 21:14  刹那的菜鸟  阅读(3319)  评论(1编辑  收藏  举报