RestSharp & WebSocket4Net 请求被中止: 未能创建 SSL/TLS 安全通道,解决方法

用C#封装的网络模块接口,用到了webSocket4Net和RestSharp,在debug的时候一开始都出现了类似以下错误:

请求被中止: 未能创建 SSL/TLS 安全通道。 
System.Net.WebException: 请求被中止: 未能创建 SSL/TLS 安全通道。
   在 System.Net.HttpWebRequest.GetResponse()
   在 RestSharp.Http.GetRawResponse(HttpWebRequest request)
   在 RestSharp.Http.GetResponse(HttpWebRequest request)

WebSocket4Net解决方法:

在实例化WebSocket的时候,指定ssl级别,Tls12;

this.websocket = new WebSocket(API_ADDR, "", null, null, "", "", WebSocketVersion.None, null, System.Security.Authentication.SslProtocols.Tls12, 0);

RestSharp解决方法:

在实例化RestSharp的时候,同样指定ssl级别,Tls12;


            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            this.client = new RestClient(API_URL);
            this.client.AddDefaultHeader("Content-Type", "application/json");

如上面只需要加一句就可以解决这个问题了。当然,在RestSharp中,还可以同时指定成这样,:

            System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

            this.client = new RestClient(API_URL);
            this.client.AddDefaultHeader("Content-Type", "application/json");

建议还是第一种方式就足够了,因为更安全

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值