SslPolicyErrors Enumeration

Namespace: System.Net.Security

Represents the errors that occurred during an SSL certificate validation.

Members

Remarks

The SslPolicyErrors enumeration is used by the RemoteCertificateValidationCallback delegate to indicate the specific reasons for SSL certificate validation failure. This allows applications to implement custom certificate validation logic and decide whether to trust a certificate despite potential issues.

When multiple errors occur, the corresponding values from the enumeration are combined using the bitwise OR operator. For example, if both the certificate chain validation failed and the name did not match, the value would be RemoteCertificateChainErrors | RemoteCertificateNameMismatch.

Usage Example

The following example demonstrates how to use SslPolicyErrors within a custom certificate validation callback.

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

public static class CustomSslPolicy
{
    public static bool ValidateServerCertificate(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            // Certificate is valid, trust it.
            return true;
        }

        // Log or inspect the specific errors for debugging.
        if (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch != 0)
        {
            // Handle name mismatch specifically, e.g., allow if it's a known alias.
            // For simplicity, we'll just log it here.
            // Console.WriteLine("Certificate name mismatch detected.");
        }

        // In a real-world scenario, you would have more sophisticated logic here
        // to decide whether to trust the certificate based on the errors.
        // For this example, we will only trust if there are NO errors.
        return false;
    }
}

// How to use it with HttpClient:
// var handler = new HttpClientHandler();
// handler.ServerCertificateCustomValidationCallback = CustomSslPolicy.ValidateServerCertificate;
// using (var client = new HttpClient(handler))
// {
//     var response = await client.GetAsync("https://your-secure-site.com");
// }
            

See Also