我对RestSharp有一个非常简单的网络请求:
var client = new RestClient("https://website.net");
var request = new RestRequest("/process", Method.GET);
request.AddParameter("cmd", "execute");
IRestResponse response = client.Execute(request);
var content = response.Content;
Console.WriteLine("Response: " + content);
这将返回错误消息:
请求已中止:无法创建 SSL/TLS 安全通道
三件事:
- 我通过浏览器得到我期望的响应,
- 我通过邮递员得到我期望的回应,
- 此请求正在发送到测试环境,但我可以将其发送到具有非常相似的地址的生产环境,并获得我期望的响应,
- 我很肯定它在今天之前就奏效了。
他们的证书使用 TLS 1.2 和 AES 128,因此它与 RC4 引起的错误无关。
这是在Visual Studio 2015中的本地Win 10计算机上,目标框架为.NET 4.5.2。
为什么我会收到此错误?
编辑:
通过更改我的代码以使用基 System.Net 和 WebRequest 类并添加以下行:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
正如这里所建议的那样,它可以工作。 所以我想 RestSharp 出于某种原因使用了不正确的协议?
在.NET 4.5
中,TLS 1.2
可用,但默认情况下未启用。
所以是的,如果你需要TLS 1.2
,你需要以某种方式为 .NET 运行时指定它。
仅供参考: 在.NET 4.7
中,.NET将使用操作系统的默认SSL/TLS版本(大多数现代操作系统将TLS 1.2
作为其默认值)
其他好的SO答案:
.NET 4.5 中的默认安全协议
即使对于Restsharp库,也使用以下行:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
以前
IRestResponse response = client.Execute(request);
会工作。
移动此行:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
在此行之前:
WebRequest request = WebRequest.Create(url);
希望有帮助。
试试这个...
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);