C# 未能创建 SSL/TLS 安全通道 和C# 基础连接已经关闭: 发送时发生错误. 解决方案

原因应该是,接口方变更了安全协议,而客户端并未启用该协议。解决办法自然就是:让客户端启用该协议。具体就是在发起网络请求之前确保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

如此即可。

事实上,这个问题正是因为我的客户端是基于.net 4.0的,而4.0的ServicePointManager.SecurityProtocol默认就不含Tls11和Tls12,所以当服务端改用这两种安全协议时,自然访问不了。

原文地址:https://www.cnblogs.com/yyangjing/p/13389667.html