小编exz*_*ly1的帖子

WebRequest错误 - 无法创建SSL/TLS安全通道

我正在尝试编写C#代码,该代码针对用于计算Web应用程序中的销售税的REST服务端点发出Web请求.这是第三方服务,使用SSL进行保护.有两种环境,UAT和生产.运行webrequest的代码如下所示:

...

var req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";

...

using (var webresponse = req.GetResponse())
{
    using (var responseStream = new StreamReader(webresponse.GetResponseStream()))
    {
        var respJson = responseStream.ReadToEnd();
        calcResult = BuildResponse(calcRequest, respJson, consoleWriteRawReqResponse);
    }
}

return calcResult;
Run Code Online (Sandbox Code Playgroud)

这对UAT环境很好.但是当我在生产环境中运行相同的代码时,我收到错误:

"无法创建SSL/TLS安全通道"

能没有问题,从邮差执行这两个请求,没有任何特殊的修改.

这导致我走上了调查这个错误的道路,我找到了很多有用的SO帖子来讨论这个话题,包括:

请求已中止:无法创建SSL/TLS安全通道

尽管设置了ServerCertificateValidationCallback,但无法创建SSL/TLS安全通道

这些帮助指向了我正确的方向,即查看将ServicePointManager.SecurityProtocol设置设置为不同的值,并使用ServicePointManager.ServerCertificateValidationCallback来调查错误.

我玩这些后发现的是以下内容:

  • UAT环境调用将使用Ssl3 |的默认设置 Tls(.NET 4.5.2的默认值),而生产环境则不会.
  • 只有当我将此设置显式设置为Ssl3时,生产调用才会起作用.

该代码如下所示:

...

var req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";

...

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback …
Run Code Online (Sandbox Code Playgroud)

c# ssl https

8
推荐指数
2
解决办法
3295
查看次数

标签 统计

c# ×1

https ×1

ssl ×1