Mar
19th | 2008

How to Use HttpWebRequest over SSL

Filed under C#, Web Development | Posted by Shahar A

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

  1. 2 Trackback(s)

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

Post a Comment

Search Dev102