底层连接已关闭。发送时发生意外错误

问题描述 投票:0回答:2

我正在尝试连接到 API。我会在前言中说,这是我们几个月前正在做的一个项目,而且它正在发挥作用,至少从某种意义上说,我可以很好地从 API 中获取数据。我们将该项目搁置了几个月,然后再回来,现在与该 API 的连接不再有效。在该项目中,我们连接到两个 API,第二个 API 连接仍然可以正常工作。我尝试在 Postman 中使用相同的标头重新创建请求,效果很好。我以前遇到过这个问题,并添加了这一行:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

过去为我解决了这个问题,但我在方法中有该代码,但现在仍然失败。

完整方法如下:

var encodedData = System.Convert.ToBase64String(
                                    System.Text.Encoding.GetEncoding("ISO-8859-1")
                                    .GetBytes("XXXXXXXXXXXXXXXXXXX:")
                                ); 

string headerString = "Basic " + encodedData;

var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxxxxxxxxxxxxxx);

httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, headerString);
httpWebRequest.KeepAlive = false;    

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
//ServicePointManager.SecurityProtocol = (SecurityProtocolType)768;   
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

Console.WriteLine("Protocol: " + ServicePointManager.SecurityProtocol);

//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
//                           SecurityProtocolType.Tls11 |
//                           SecurityProtocolType.Tls12;

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();   
    
    writelog("Result: " + result);
}

不确定这是否有帮助,但是当我尝试分析 Fiddler 中的流量时,我可以很好地看到来自 Postman 的请求,但是当我运行上面的代码时,我从来没有得到任何流量离开我的网络。从 localhost 到 /vshub/XXXXXXXXXXX 的流量非常大。我还尝试了

ServicePointManager.SecurityProtocol
的其他排列,正如您从注释掉的代码中看到的那样,但没有一个有效。

我对解决这个问题束手无策。 任何帮助,将不胜感激! 哦,我在

runtime 4.0
framework 4.6

更新:使用相同的运行时和框架在备用机器上运行代码,并且运行良好。这似乎越来越有可能是我本地计算机上的防火墙问题。

c# .net httpwebrequest
2个回答
4
投票

这实际上是与TLS协议相关的问题。 在致电服务之前使用此功能应该可以解决问题,

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

2
投票

我解决了。我尝试在其他机器上全新安装 Visual Studio 来运行代码。它在所有其他机器上运行良好。我在本地计算机上重新安装了 VS,代码就可以工作了。不确定过去一两个月我的 VS 发生了什么变化,但显然有些东西已经损坏了。

© www.soinside.com 2019 - 2024. All rights reserved.