例外:底层连接已关闭:无法为SSL / TLS安全通道建立信任关系

时间:2017-01-07 09:32:06

标签: c# web-services iis-6 firebase-notifications windows-server-2003-r2

火力通知代码的

WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); 
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new{collapse_key = "unassigned", to = deviceToken,data = new
  {body = message,title = title,sound = "default"}
};

要在移动设备上传递通知的消息

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationId));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
代码

下面出现

错误

using (Stream dataStream = tRequest.GetRequestStream())
{ 
  dataStream.Write(byteArray, 0, byteArray.Length);
 using (WebResponse tResponse = tRequest.GetResponse())
  { 
    using (Stream dataStreamResponse = tResponse.GetResponseStream())
    { 

   //code 1
    }     
  }   
}  

4 个答案:

答案 0 :(得分:7)

标题中的例外表明您正在使用TLS加密连接到端点,并且您不信任该端点公开的证书。这意味着未使用您在CA(证书颁发机构)存储中拥有的证书进行签名。就像自签名证书一样。

如果证书是自签名的,您可以将其添加到CA Store。如果没有,您可以尝试使用浏览器导航端点,并查找显示端点(或实际在证书链上签名的端点)的证书副本,下载然后将其添加到你的商店。

您还可以通过添加始终返回有效的自定义证书验证处理程序来避免此检查! (真正)。 但请注意,这样做会让您受到中间人攻击,因为您将无法检查端点的无效性

ServicePointManager
    .ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;

答案 1 :(得分:1)

我不知道为什么要使用上面提到的这行代码

ServicePointManager
    .ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;

我无法使其发挥作用

所以,但以这种方式使用它可以正常工作:

internal static bool ValidateServerCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}
ServicePointManager.ServerCertificateValidationCallback  = ValidateServerCertificate;

答案 2 :(得分:0)

这对我有用。

ServicePointManager
  .ServerCertificateValidationCallback += 
  (sender, cert, chain, sslPolicyErrors) => true;

无论有无,我都对其进行了多次测试。绝对解决了这个问题。

答案 3 :(得分:0)

  1. 调用网站和API站点应具有相同的SSL证书 我使用“ IIS Express开发证书”

  2. 将证书导出到本地文件 Export Certificate

  3. 将证书导入到“ ConsoleCertificate”中的“受信任的根证书颁发机构”文件夹中

Import it into trust root