System.Net.WebException when using WebClient: Can not create SSL/TLS secure channel

BennoDual picture BennoDual · Mar 23, 2015 · Viewed 18.3k times · Source

When I execute the following code

System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => {
    return true;
};
var webClient = new WebClient();
var s = webClient.DownloadString("https://jtlplugins.x-volution.de/api.php?apikey=yS5VS7OiG1ukiIqLzCSYuFCjeF1qSskKOQeCtVxh&do=pruefe_app&cappid=123&chardwareid=DC0D-BFEA-6F79-58DE-21E9-BA3A-B288-C46F&clizenzschluessel=123");

I always get a System.Net.WebException: Can not create SSL/TLS secure channel

When I execute this

https://jtlplugins.x-volution.de/api.php?apikey=yS5VS7OiG1ukiIqLzCSYuFCjeF1qSskKOQeCtVxh&do=pruefe_app&cappid=123&chardwareid=DC0D-BFEA-6F79-58DE-21E9-BA3A-B288-C46F&clizenzschluessel=123

for example direct in Firefox or Internet Explorer, it works and give back a result.

What should I do that this is also executed with my code like in the browser?

I have read the other posts in stackoverflow about this problem - but they are not solving my problem :-(

Answer

kmcnamee picture kmcnamee · Mar 23, 2015

If you close fiddler (if you have it open) and add the following the exception should go away

ServicePointManager.Expect100Continue = true;                
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Or at least it did for me when i tried your code like so

try
{
     ServicePointManager.Expect100Continue = true;                
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

     var webClient = new WebClient();

     var s = webClient.DownloadString("https://jtlplugins.x-volution.de/api.php?apikey=yS5VS7OiG1ukiIqLzCSYuFCjeF1qSskKOQeCtVxh&do=pruefe_app&cappid=123&chardwareid=DC0D-BFEA-6F79-58DE-21E9-BA3A-B288-C46F&clizenzschluessel=123");

     MessageBox.Show("Result" + s);
}
catch(Exception ex)
{ 
  MessageBox.Show(ex.Message); 
}
  • Insecure code warning - Even though i am assuming you already know this and is not why your were getting a WebException with your code, I am adding a warning for potential future readers in the decades following the original posting of this question. The code:

    System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => { return true; };

Will ignore any certificate validation errors and therefor by definition is not exactly secure. Please see the question C# Ignore certificate errors?