Directory Freebies VS CheatSheet Forum

RSS

Email

Translate

Home About Archive Privacy Contact Advertise Write for Dev102
Posted by Shahar A on Mar 19th, 2008 | Filed under C#, Web Development |

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: , , , , ,

3 Responses to “How to Use HttpWebRequest over SSL”


  1. Peter Said on Jun 15, 2009 :

    That solution worked perfectly! Thanks!

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

Write Article for Dev102

Write for Dev102!

We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution

Learn More