C# Ignore certificate errors?

后端 未结 11 1029
鱼传尺愫
鱼传尺愫 2020-11-22 15:01

I am getting the following error during a web service request to a remote web service:

Could not establish trust relationship for the SSL/TLS secure c

11条回答
  •  情歌与酒
    2020-11-22 15:25

    Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

    .Net core:

    using (var httpClientHandler = new HttpClientHandler())
    {
        httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;   //Is valid
            }
    
            if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
            {
                return true;
            }
            return false;
        };
        using (var httpClient = new HttpClient(httpClientHandler))
        {
            var httpResponse = httpClient.GetAsync("https://example.com").Result;
        }
    }
    

    .Net framework:

    System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }
    
        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
    
        return false;
    };
    

    Update:

    How to get cert.GetCertHashString() value in Chrome:

    Click on Secure or Not Secure in the address bar.

    Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower().

提交回复
热议问题