最近项目改造https,有部分请求出现“请求被中止: 未能创建 SSL/TLS 安全通道”。
原因应该是,接口方变更了安全协议,而客户端并未启用该协议。
解决办法自然就是:让客户端启用该协议。具体就是在发起网络请求之前确保ServicePointManager.SecurityProtocol中含有服务端所用的安全协议,如果不知道或希望客户端健壮一点,当然最简单的方式就是把所有可用的协议都启用,随你服务端将来怎么换。代码如下:
if (url.ToLower().StartsWith("https"))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
}
上线后,发现部分接口请求还是会出现上面问题。
经过分析发现,
1.都是同一套架构,不会存在配置或其他问题。
2.接口有时可以有时不可以(初步怀疑有节点没部署上)
3.分析日志发现大部分都是请求时间长的接口返回的。
结论:
如果请求超时
http请求,会返回——> GatewayTimeout
https请求会返回——> 请求被中止: 未能创建 SSL/TLS 安全通道。
出处:www.cnblogs.com/bigbrid
更新:
将一些超市接口异步执行,经过一段时间发现,SSL/TLS 问题还是会有出现
发现了还要加上下面这些配置
ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
经过验证已经大大降低了,但还是没有杜绝。
如有更好的方案,欢迎沟通交流。
参考:https://smalltool.github.io/2020/08/24/Could-not-create-SSL-TLS-secure-channel/