How do I use WebRequest to access an SSL encrypted site using https?

Alfred B. Thordarson picture Alfred B. Thordarson · Feb 18, 2009 · Viewed 179.3k times · Source

I'm writing a program that reads content from a user provided URL. My problem is in the code that goes something like this:

Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());

And this is breaking if the provided url is an "https://" URL. Can anyone help me with changing this code so that it will work with SSL encrypted content. Thanks.

Answer

LukeDuff picture LukeDuff · Feb 18, 2009

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}