Ole Albers
Ole Albers

Reputation: 9295

Resetting ServerCertificateValidationCallback

I need to access a REST service that has an SSL certificate which isn't really valid. So I added the following in my code:

 System.Net.ServicePointManager.ServerCertificateValidationCallback = 
    ((sender, cert, chain, errors) =>
       cert.Subject.Contains("soap.example.com"));

After that I do what I have to do to send the request to REST service.

Everything is fine.

But lateron I need to connect to a different domain (which has a valid SSL certificate). The the latter fails because of a certificate error that disappears if I restart the IIS and only comes back after the code segment displayed above is called again:

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

So after sending the request to the REST service with invalid certificate, how can I make sure, the normal behavior is working again?

Simply resetting to ServerCertificateValidationCallback=null does not seem to work.

(I am fully aware about the dangers of the CallBack)

Upvotes: 0

Views: 1210

Answers (1)

mjwills
mjwills

Reputation: 23898

System.Net.ServicePointManager.ServerCertificateValidationCallback = 
        ((sender, cert, chain, errors) => 
        errors == SslPolicyErrors.None || cert.Subject.Contains("soap.example.com"));

should do the trick.

Upvotes: 2

Related Questions