C# Web 请求 w RestSharp - “请求已中止:无法创建 SSL/TLS 安全通道”

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

我有一个使用 RestSharp 的极其简单的 Web 请求:

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 安全通道

三件事:

  1. 我通过浏览器得到了我期望的响应,
  2. 我通过邮递员得到了我期望的回复,
  3. 此请求正在发送到测试环境,但我可以将其发送到具有非常相似的地址的生产环境,并获得我期望的响应,
  4. 我确信它在今天之前就有效了。

他们的证书使用 TLS 1.2 和 AES 128,因此与 RC4 引起的错误无关。

这是在我的本地 Win 10 计算机上的 Visual Studio 2015 中,目标框架为 .NET 4.5.2。

为什么我会收到此错误?

编辑:

通过更改我的代码以使用基本 System.Net 和 WebRequest 类并添加以下行:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

按照here的建议,它有效。 所以我猜 RestSharp 由于某种原因使用了不正确的协议?

c# restsharp
5个回答
21
投票

即使对于 Restsharp 库,也可以使用以下行:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

之前

IRestResponse response = client.Execute(request);

会起作用的。


18
投票

.NET 4.5
中,
TLS 1.2
可用,但默认不启用

所以是的,如果您需要

TLS 1.2
,您需要以某种方式为 .NET 运行时指定它。

仅供参考: 在

.NET 4.7
中,.NET 将使用操作系统的默认 SSL/TLS 版本(大多数现代操作系统将
TLS 1.2
作为默认版本)


其他好的SO答案:

.NET 4.5 中的默认安全协议


7
投票

移动此行:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

在此行之前:

WebRequest request = WebRequest.Create(url);

希望有帮助。


0
投票

试试这个...

ServicePointManager.ServerCertificateValidationCallback = new        
RemoteCertificateValidationCallback
(
   delegate { return true; }
);

0
投票

我遇到了同样的问题。设置 SecurityProtocol 没有解决问题。

request.AlwaysMultipartFormData = false; 

很好地解决了我的问题。

注意:它已经默认为False。但由于我的流程,我将其设置为 True。你可能也在这样做。只要确保它是假的

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