C#使用RestSharp发起Web请求报错:无法创建SSL/TLS安全通道
解决RestSharp请求中"Could not create SSL/TLS secure channel"错误
这个问题我之前也碰到过,大概率是你的程序默认使用的SSL/TLS版本和目标服务器要求的不匹配——毕竟浏览器能正常访问,说明服务器本身的SSL配置是没问题的。
直接给你最常用的解决方案:
- 在创建RestClient之前,强制指定程序使用较新的TLS版本,比如TLS 1.2或1.3。添加这行代码:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
修改后的完整代码如下:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; 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);
补充说明:
- 如果你用的是.NET Framework,这一步几乎是必须的,因为旧版本框架默认不会启用TLS 1.2/1.3;
- 要是还是不行,可以检查服务器证书是否在你的系统信任根里,但既然浏览器能访问,这个可能性比较小;
- 对于.NET Core/.NET 5+的项目,有时候默认会自动协商合适的协议,但如果遇到问题,加上这行代码也不会有负面影响。
内容的提问来源于stack exchange,提问作者Gerald
相关产品推荐
相关产品推荐

