【问题标题】:RestSharp request aborted - could not create SSL/TLS secure channelRestSharp 请求中止 - 无法创建 SSL/TLS 安全通道
【发布时间】:2018-10-10 06:32:55
【问题描述】:

我正在尝试使用 RestSharp 使用以下代码在本地机器上测试 API 调用...

        var client = new RestClient("https://[API URL]");

        var request = new RestRequest( Method.POST);
        request.AddParameter("session", this, ParameterType.RequestBody);

        IRestResponse<SessionOut> response = client.Execute<SessionOut>(request);
        return response.Data.session.id;

response 中,我收到一条错误消息,告诉我请求已中止,因为它“无法创建 SSL/TLS 安全通道”。

这是否意味着我需要尝试设置 https://localhost 而不是 http://localhost 才能在 https:// 地址调用 API?

更新

根据@Shai_Aharoni 下面的回答,我已将我的代码更新为以下内容。但是,我仍然遇到同样的错误。

        string pathToYourClientCert = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "[my certificate file");
        var client = new RestClient("[API URL]/");
        client.ClientCertificates = new X509CertificateCollection();
        client.ClientCertificates.Add(new X509Certificate(pathToYourClientCert));

        var request = new RestRequest( Method.POST);
        request.AddParameter("session", this, ParameterType.RequestBody);

        IRestResponse<SessionOut> response2 = client.Execute<SessionOut>(request);

【问题讨论】:

  • 你的系统有代理吗,stackoverflow.com/a/47675172/713789
  • 没有 @AnirudhaGupta ,只是直接从 localhost 测试到 API。
  • 查看@Shai 的回答,如果效果不好,可以在Postman 和HttpClient 中测试吗,如果显示相同,则需要在您的机器中安装该证书。这个答案应该有效。

标签: c# asp.net ssl restsharp


【解决方案1】:

尝试将此添加到您的代码中:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

相关资源:

【讨论】:

    【解决方案2】:

    嗯...在调用 HTTPS 端点之前,您需要完成几个步骤。

    1) 确保您的服务器支持 HTTPS 端点(即:URL https://[APIURL] 是可访问的。

    2) 在执行 HTTPS 调用的机器上安装有效的服务器(api 服务器)证书。

    3) 将证书添加到您的 RestSharp 客户端。类似于这样:

    string pathToYourClientCert = "cer/cert.cer";
    client.ClientCertificates.Add(new X509Certificate(pathToYourClientCert));
    

    希望这会有所帮助...

    【讨论】:

    • 感谢@Shai_Aharoni,我已经添加了证书加载代码,但仍然出现相同的错误。证书在 IIS 中创建并使用 mmc.exe 导出。该网站在 https:// 运行(由于自创证书而发出警告)查看我的更新答案。
    【解决方案3】:

    按照以下步骤操作: https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/http-stack?tabs=macos

    还要在 MainActivity.cs -> OnCreate -> 加载应用之前将此添加到您的代码中:

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

    为了让我的 API 请求在 Xamarin Forms 中工作,我必须同时执行这两项操作!

    确保您的证书不是自签名的!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2017-04-20
      • 2021-02-27
      • 2012-06-05
      • 2018-04-22
      相关资源
      最近更新 更多