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.

Tags :

4 Responses to “How to Use HttpWebRequest over SSL”

  1. Peter

    Said on June 15, 2009 :

    That solution worked perfectly! Thanks!

  2. BodzioM

    Said on May 19, 2012 :

    Very Very helpfull solusion. Thx

2 Trackback(s)

  1. Mar 27, 2008: DotNetKicks.com
  2. Mar 31, 2008: Wöchentliche Rundablage: WPF, Silverlight 2, ASP.NET MVC, .NET 3.5… | Code-Inside Blog

Post a Comment