重庆熊猫 Loading

.NET 处理[未能为 SSLTLS 安全通道建立信任关系]问题

更新记录
2022年4月16日本文迁移自Panda666原博客,原发布时间:2021年7月16日。

在.NET的开发过程中,发现[基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系]问题。在PowerShell的使用过程中,也发现该问题。因为PowerShell本身就是基于.NET开发的,所以遇到同样的问题也就不奇怪了。最新版本的PowerShell基于.NET Core开发的,已经跨平台了,喜欢的朋友可以试试看。
image

PowerShell中解决办法

在调用Invoke-Webrequest命令时,出现该错误,解决办法是调用命令前,使用以下设置:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
Invoke-WebRequest "panda666.com"

.NET开发C#中解决办法

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

namespace ConsoleApp1
{
    class Program
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            // 总是接受  
            return true;
        }

        static void Main(string[] args)
        {
            //Your Code

            //验证服务器证书回调自动验证
            ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;

            //Your Code
            //wait
            Console.ReadKey();
        }
    }
}
posted @ 2022-04-16 18:57  重庆熊猫  阅读(748)  评论(0编辑  收藏  举报