使用WebClient时的System.Net.WebException:无法创建SSL / TLS安全通道

当我执行以下代码时

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"); 

我总是得到一个System.Net.WebException:无法创建SSL / TLS安全通道

当我执行这个

 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 

例如,直接在Firefox或Internet Explorer中,它可以工作并返回结果。

我应该怎么做,这也是我的代码在浏览器中执行的?

我已经阅读了stackoverflow中有关此问题的其他post – 但他们没有解决我的问题:-(

如果你关闭fiddler(如果你打开它)并添加以下内容,则exception应该消失

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

或者至少它在我尝试你的代码时为我做了

 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); } 
  • 不安全的代码警告 – 即使我假设您已经知道这一点,并且不是您的代码获得WebException的原因,我在最初发布此问题后的几十年内为潜在的未来读者添加了警告。 代码:

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

将忽略任何证书validation错误,因此根据定义并不完全安全。 请参阅问题C#忽略证书错误?