System.Net.CertificatePolicy to ServerCertificateValidationCallback Accept all certificate policies

☆樱花仙子☆ 提交于 2019-12-30 02:17:26

问题


I've downloaded some sample code that is a bit outdated. It has the following class:

public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
    public TrustAllCertificatePolicy()
    { }

    public bool CheckValidationResult(ServicePoint sp,
              System.Security.Cryptography.X509Certificates.X509Certificate cert,
              WebRequest req, 
              int problem)
    {
        return true;
    }
}

later on in the code it calls the following:

System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

It gives the following warning:

Warning 1 'System.Net.ServicePointManager.CertificatePolicy' is obsolete: 'CertificatePolicy is obsoleted for this type, please use ServerCertificateValidationCallback instead. http://go.microsoft.com/fwlink/?linkid=14202'

What is the current procedure to achieve the equivalent functionality?

I've read an article on MSDN but I'm unsure of how to convert? This is for a class library. I appologize if it seems as though I havn't researched this enough but when it comes to ssl certificates, it's a bit out of my realm. Any help is greatly appreciated!


回答1:


Include the following class in your code

 public static class SSLValidator
        {
            private static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain,
                                                      SslPolicyErrors sslPolicyErrors)
            {
                return true;
            }
            public static void OverrideValidation()
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    OnValidateCertificate;
                ServicePointManager.Expect100Continue = true;
            }
        }

Then call the following before you make service call but be careful to remove this code on the production when you have real certs

SSLValidator.OverrideValidation();  

Or you can do the following to use it only for debugging

#if DEBUG

            SSLValidator.OverrideValidation();
#endif 



回答2:


I use the following when connecting to other web services.

//workaround for SSL certificate issue
ServicePointManager.ServerCertificateValidationCallback = 
  (sender, certificate, chain, sslPolicyErrors) => { return true; };

per comments I need to add to the blurb - DO NOT DO THIS IN PRODUCTION (if you do - please send $500 to my paypal account)



来源:https://stackoverflow.com/questions/18454292/system-net-certificatepolicy-to-servercertificatevalidationcallback-accept-all-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!