Calling web services with an invalid SSL certificate
Posted: (EET/GMT+2)
Sometimes, you will want to call a web service from C# code, but the web server's HTTPS (SSL) certificate is invalid or gives errors because it is not fully validated by a certificate authority (CA) such as VeriSign. For instance, this certificate could be a custom certificate to you've created yourself for testing purposes.
However, when you call such a web service from .NET code, the call will fail with an exception because of the invalid certificate. But as you could guess, there's a piece of code that you can do to trust the certificate nonetheless and work around the issue. The ServicePointManager class in the System.Net namespace contains a property named RemoteCertificateValidationCallback to which you can assign your custom event handler. Here's an example with .NET 2.0:
private void SetupCertificates()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
new System.Net.Security.RemoteCertificateValidationCallback(
MyCertificateErrorHandler);
}
private bool MyCertificateErrorHandler(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// do testing here
...
// yes, we trust this certificate
return true;
}
The event handler (delegate) must be of the type RemoteCertificateValidationCallback from System.Net.Security. Of course, you can make the code cleaner with these three using statements:
using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates;