共用方式為


How to skip server certificate validation error when using HTTPS?

When you are developing a WCF service with an HTTPS endpoint (i.e., you enabled Transport security), you would want to test it with a test certificate or a certificate which has some invalid data. The former can happen when you create the certificate with the tool MakeCert.exe. The latter can happen when you use the host name “localhost” instead of the one that matches the subject of the certificate. In this case, you would need to skip the certificate validation error during service development cycle. To skip the error, the simplest thing is to register to the static System.Net API ServicePointManager.ServerCertificateValidationCallback. Here is a short example:

public static void Main(string[] args)

{

    System.Net.ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(

        RemoteCertValidate);

    // Invoking the service over HTTPS

    // ...

}

static bool RemoteCertValidate(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)

{

    System.Console.WriteLine("WARNING: Got server certificate error: {0}", error);

    if (string.Compare(cert.Subject, "CN=FooCertificate") == 0)

    {

        // NOTE: This should be only used for development phase. You need to remove it in the deploymnet environment!

        return true;

    }

    return false;

}

Comments

  • Anonymous
    August 16, 2007
    PingBack from http://msdnrss.thecoderblogs.com/2007/08/17/

  • Anonymous
    July 20, 2014
    just add below code:                System.Net.ServicePointManager.ServerCertificateValidationCallback +=                    delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,                                            System.Security.Cryptography.X509Certificates.X509Chain chain,                                            System.Net.Security.SslPolicyErrors sslPolicyErrors)                    {                        return true; // **** Always accept                    };