【问题标题】:C# Web Request w RestSharp - "The request was aborted: Could not create SSL/TLS secure channel"C# Web 请求 w RestSharp -“请求被中止:无法创建 SSL/TLS 安全通道”
【发布时间】:2018-09-27 21:03:22
【问题描述】:

我有一个非常简单的使用 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 安全通道

三件事:

  1. 我通过浏览器获得了预期的响应,
  2. 我通过 Postman 得到了预期的响应,
  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 出于某种原因使用了不正确的协议?

【问题讨论】:

  • 网站证书有效吗?如果不是,您将需要处理 CertificateCallback 并手动验证
  • 您的目标是哪个 .NET Framework/版本?你的操作系统是什么?这发生在您的(本地开发)机器还是(生产)服务器上?
  • 查看 Windows 事件查看器以获得比 Windows 提供的一般消息更深入的错误原因。您应该能够从那里获得 TLS 错误代码。
  • 我出于好奇下载了源代码(以前从未使用过 RestSharp)。在内部,它使用 System.Net.HttpWebRequest(继承 WebRequest)。我还遇到了在内部捕获异常并将其设置为 response.ErrorMessage 的代码(因此在某处引发了异常)。添加启用 TLS1.2 的行是否可以与您拥有的 RestSharp 代码一起使用?

标签: c# restsharp


【解决方案1】:

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

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

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


其他好的 SO 答案:

Default SecurityProtocol in .NET 4.5

【讨论】:

    【解决方案2】:

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

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    之前

    IRestResponse response = client.Execute(request);
    

    会起作用的。

    【讨论】:

      【解决方案3】:

      移动这一行: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

      在这一行之前: WebRequest 请求 = WebRequest.Create(url);

      希望对您有所帮助。

      【讨论】:

      • 这听起来不像是一个答案,或者?
      【解决方案4】:

      试试这个...

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-05
        • 2018-04-22
        • 2012-10-30
        相关资源
        最近更新 更多