How to ignore a certificate error with c# 2.0 WebClient - without the certificate

后端 未结 6 2111
时光说笑
时光说笑 2020-11-28 06:42

Using Visual Studio 2005 - C# 2.0, System.Net.WebClient.UploadData(Uri address, byte[] data) Windows Server 2003

So here\'s a stripped down version of

6条回答
  •  孤独总比滥情好
    2020-11-28 07:08

    I wanted to disable SSL verification for a specific domain without globally deactivating it because there might be other requests running which should not be affected, so I came up with this solution (please note that uri is a variable inside a class:

            private byte[] UploadValues(string method, NameValueCollection data)
            {
                var client = new WebClient();
    
                try
                {
                    ServicePointManager.ServerCertificateValidationCallback +=
                        ServerCertificateValidation;
    
                    returnrclient.UploadValues(uri, method, parameters);
    
                }
                finally
                {
                    ServicePointManager.ServerCertificateValidationCallback -=
                        ServerCertificateValidation;
                }
            }
    
            private bool ServerCertificateValidation(object sender,
                X509Certificate certificate, X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
            {
                var request = sender as HttpWebRequest;
                if (request != null && request.Address.Host.Equals(
                    this.uri.Host, StringComparison.OrdinalIgnoreCase))
                    return true;
                return false;
            }
    

提交回复
热议问题