HtmlAgilityPack进行的Web查询引发System.Net.WebException:请求已中止:无法创建SSL/TLS安全通道

问题描述:

从我读到的几个主题中,绝大多数与Paypal有关,而其他一些与ServicePointManager有关.这与其他问题无关!在这种情况下,我只是尝试一个基本的HTML敏捷包示例,而该示例与Paypal或ServicePointManger无关:

From the several topics on this I read, the vast majority are in relation to paypal, and a few other are in relation to something called ServicePointManager. This has NO RELATION to the other problems! In this case I'm just trying a basic html agility pack example with no relation to paypal or ServicePointManger:

        var url = "some_url";
        var web = new HtmlWeb();

      var doc = web.Load(url); 

标记的行将引发此错误:

And the marked line throws this error:

Unhandled Exception: System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.HttpWebRequest.GetResponse()
   at HtmlAgilityPack.HtmlWeb.Get(Uri uri, String method, String path, HtmlDocument doc, IWebProxy proxy, ICredentials creds) in C:\something\HtmlAgilityPack\HtmlAgilityPack.Shared\HtmlWeb.cs:line 1677
   at HtmlAgilityPack.HtmlWeb.LoadUrl(Uri uri, String method, WebProxy proxy, NetworkCredential creds) in C:\Users\Jonathan\source\repos\HtmlAgilityPack\HtmlAgilityPack.Shared\HtmlWeb.cs:line 2086
   at HtmlAgilityPack.HtmlWeb.Load(Uri uri, String method) in C:\something\HtmlAgilityPack\HtmlAgilityPack.Shared\HtmlWeb.cs:line 1300
   at HtmlAgilityPack.HtmlWeb.Load(String url) in C:\something\HtmlAgilityPack\HtmlAgilityPack.Shared\HtmlWeb.cs:line 1197
   at DownloadSeco.Program.Main(String[] args) in C:\something\Program.cs:line 16

究竟是什么导致此错误,以及如何解决该错误?

What exactly causes this error and how does one fix it?

我正在关闭该主题,显然问题出在我的特定计算机上,因为它可以在我旁边的PC上运行.

I'm closing the topic apparently the issue is with my specific computer, since it works on the pc next to me.

据我了解,Paypal已更新为TLS版本.详细信息请此处.

As I understand the Paypal have been updated TLS version. Details are here.

但是.NET默认情况下不支持TLS1.2.

But .NET does not support TLS1.2 by default.

您需要手动启用它.

您可以使用以下代码进行操作:

You can do it using next code:

System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

SecurityProtocol是Singleton.而且,您可以在应用程序中一次设置TLS(而不是为每个WebRequest设置一次).您可以在Program.cs文件中设置TLS.

The SecurityProtocol it is Singleton. And you can set TLS one time in your application (not for each WebRequest). You can set TLS in your Program.cs file.

另外,请详细阅读本SO 主题.

Also please review this SO topic for details.