If you try to use HttpWebRequest for calling secured sites, and you are getting the following exception: “The underlying connection was closed: Could not establish trust relationship with remote server” here is what’s happening and how you can (hopefully) solve it:
When browsing to a secured site with your web browser, you get a dialog asking if you trust the certificate provided by the server. If you invoke a web service or scrapping a site which uses SSL you have to solve this in code, by setting a callback for validating the server certificate. In this example I’ll demonstrate how to accept all requests, any other logic can be implemented…
Define the callback:
public static bool AcceptAllCertificatePolicy(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
The returned value determines whether the specified certificate is accepted for authentication.
Then set:
ServicePointManager.ServerCertificateValidationCallback += AcceptAllCertificatePolicy;
see ServicePointManager documentation in msdn.
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More
Peter Said on Jun 15, 2009 :
That solution worked perfectly! Thanks!