我正在尝试连接到API。我将为此做一个开头,并说这是我们几个月前正在研究的项目,并且它正在起作用,至少在某种意义上说,我可以伸出手并从API中很好地获取数据。我们将项目搁置了几个月,然后又恢复了,现在与该API的连接不再起作用。在项目中,我们正在连接2个API,第二个API连接仍然可以正常工作。我尝试使用邮递员中的相同标头重新创建请求,并且工作正常。我以前有这个问题,并添加以下行:
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的请求很好,但是当我运行上述代码时,我从未收到任何流量离开我的网络。从本地主机到/ vshub / XXXXXXXXXXX的流量非常多。从注释掉的代码中可以看到,我还尝试了ServicePointManager.SecurityProtocol
的其他排列,但是没有一个起作用。
我很想解决这个问题。
任何帮助,将不胜感激!
哦,我在runtime 4.0
和framework 4.6
上。
更新:使用相同的运行时和框架在备用计算机上运行代码,并且工作正常。我的本地计算机上似乎越来越有防火墙问题。
非常感谢!
答案 0 :(得分:3)
这实际上是与TLS协议有关的问题。 在致电服务之前使用此功能应该可以解决问题,
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
答案 1 :(得分:1)
我解决了。我尝试使用全新安装的Visual Studio在其他计算机上运行代码。它在所有其他机器上都能正常工作。我在本地计算机上重新安装了VS,并且代码正常工作。不知道在过去一两个月中我的VS发生了什么变化,但是显然有损坏。