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

问题描述 投票:4回答:3

用于firebase通知代码

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
    }     
  }   
}  
c# web-services iis-6 firebase-notifications windows-server-2003-r2
3个回答
7
投票

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

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

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

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

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;

0
投票

这对我有用。

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

我有没有测试过几次。绝对照顾好这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.