C# Web 异常意外的 EOF

C# Web exception unexpected EOF

我正在尝试从 imdb 下载 json 网页以查找演员。

        try
        {
            using (WebClient wc = new WebClient())
            {
                string content = wc.DownloadString("https://v2.sg.media-imdb.com/suggests/names/b/brad.json");
            }
        }
        catch (WebException x)
        {
            x.ToString();
        }

每当我尝试进行下载时。

给出的异常是:

The underlying connection was closed: An unexpected error occurred on a send.

而内网异常是:

Received an unexpected EOF or 0 bytes from the transport stream.

根据我的阅读。发生这种情况是因为 imdb 的其中一台服务器配置错误。

为了尝试解决这个问题,我使用了

System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(3072);

将安全协议设置为 Tls12,这确实解决了我 PC 上的问题。

但是,当我尝试在我的第二台 PC 上使用它时。该行抛出异常:

System.NotSupported: The requested security protocol is not supported

我认为这意味着它在该 PC 上不支持 tls12。

我在那台 PC 上安装了 .NET Framework 4.5.1,但我无法安装 .NET Framework 4.7,因为它安装失败。

我假设安全协议随 4.7 一起提供,但我没有在 MSDN 上看到这一点。

如何在第二台 PC 上下载网页?

有没有办法让我手动安装 Tls12 协议?

是否有使用 HttpWebRequest 或某些独立可执行文件的替代方法?

我强烈建议更新到最新的 .Net Framework“4.7.X”。

根据Microsoft Documentation

Starting with the .NET Framework 4.7, the default value of this property is SecurityProtocolType.SystemDefault. This allows .NET Framework networking APIs based on SslStream (such as FTP, HTTP, and SMTP) to inherit the default security protocols from the operating system or from any custom configurations performed by a system administrator.

因此从理论上讲,更新到最新的 .Net Framework 应该可以解决问题,而无需更改任何系统注册表值,例如,支持较低的 TLS 版本或覆盖 Framework 默认行为。

另外,它只能在您的机器上运行的原因可能是,您的机器支持 TLS 1.2,而另一台机器不支持。

检查您是否可以检查启用版本的注册表:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols

如果您需要启用 TLS 1.2(如果定期更新,默认情况下应该启用),您可以查看以下文章:

https://support.microsoft.com/en-us/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi

https://www.itnota.com/enabling-tls-1-2-default-security-protocol-windows-servers/

总结一下:

  • 尝试更新到最新的 .Net Framework。
  • 如果不可能 然后使用

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

  • 如果它在另一台机器上不起作用,请检查支持的 TLS 本机版本

.

我最终使用了 cURL 二进制文件,因为它不依赖于 .NET Framework。