一切福田,不離方寸,從心而覓,感無不通。

.net 请求https接口时出现 基础连接已经关闭: 发送时发生错误,使用postman测试可以正常访问

在后台代码中进行基于https协议的请求时,我们经常会遇到一个错误:The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel(基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系。)

1,先加入命名空间:

using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

2,再重载CheckValidationResult方法,返回true

private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}

3.然后在执行请求的代码之前加上

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;

通过以上三步忽略证书的错误,但是不安全,其他解决方式可以参考https://stackoverflow.com/questions/703272/could-not-establish-trust-relationship-for-ssl-tls-secure-channel-soap

 

然而,对于一些https接口,加了上述代码之后,调用时回报错:基础连接已经关闭: 发送时发生错误

发生该错误的原因是,使用上述代码默认是以ssl安全协议进行的,但是有些https接口服务并没有使用ssl安全协议,具体参考

https://stackoverflow.com/questions/28286086/default-securityprotocol-in-net-4-5

解决方案1:硬编码,枚举出所有的安全协议,比较简单

在ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;这行代码前面加上如下代码:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

解决方案2:让OS自动选择安全协议(推荐)

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls

 

from:https://blog.csdn.net/ujm097/article/details/89334667