首页 > 解决方案 > 从传输流接收到意外的 EOF 或 0 字节。ServicePointManager 的设置无法修复

问题描述

当我尝试使用 WebClient 下载字符串时出现该异常。我尝试了很多案例来设置 ServicePointManager:

ServicePointManager.Expect100Continue: true and false
ServicePointManager.SecurityProtocol: SecurityProtocolType.Ssl3 

SecurityProtocolType.Tls12 

(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12) 

以及所有 Tls 和所有协议。每种组合都被使用了。不工作。
但是如果我使用 curl 命令 - 我会很好地获得 json。

curl -X GET https://myurl/2019-05-29


来自浏览器系统的相同行为: Windows Server 2012 R2
.NET:Framework 4.6.1

调用栈
Failed to get fixtures from URI=https://myurl/2019-05-29. System.Net.WebException: An exception occurred during a WebClient request. --->System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream. at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.WebClient.DownloadBitsState.RetrieveBytes(Int32& bytesRetrieved) at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp) at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) --- End of inner exception stack trace --- at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadString(Uri address) at System.Net.WebClient.DownloadString(String address)

一种情况下的代码:

ServicePointManager.ServerCertificateValidationCallback +=
              (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                                       SecurityProtocolType.Tls11 | 
                                       SecurityProtocolType.Tls12 |
                                       SecurityProtocolType.Ssl3;

using (var wc = new WebClient())
{
    try
    {
       var json = wc.DownloadString(uri);
       return json;
    }
    catch (Exception e)
    {
        return null;
    }
}

标签: c#.netweb

解决方案


推荐阅读