我正在使用公共Root权威证书文件X509制作httpwebrequest.我只有公钥,而不是私钥.从控制台应用程序一切正常,但它不能从asp.net应用程序.我收到错误:"底层连接已关闭:无法为SSL/TLS安全通道建立信任关系."
禁用验证的选项不是一个选项.
这是代码
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://xxxxxxx/gateway.aspx"); string post = "abcdef"; req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; req.ContentLength = post.Length; var cert = System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(@"c:\temp\root.cer"); req.ClientCertificates.Add(cert); StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(post.ToString()); stOut.Close(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
这是System.Net和System.Net套接字的系统日志.
System.Net信息:0:[5928] SecureChannel#8106798 - 无法将证书链构建到受信任的根颁发机构.
System.Net信息:0:[5928] SecureChannel#8106798 - 用户验证远程证书无效.
System.Net.Sockets详细:0:[5928]套接字#7486778 :: Dispose()
System.Net错误:0:[5928] HttpWebRequest中的异常#51319244 :: - 底层连接已关闭:无法为SSL/TLS安全通道建立信任关系.
System.Net错误:0:[5928] HttpWebRequest中的异常#51319244 :: EndGetRequestStream - 底层连接已关闭:无法为SSL/TLS安全通道建立信任关系.
更多信息
如果我使用此代码(来自CodeGuru)
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) { return false; } else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) { System.Security.Policy.Zone z = System.Security.Policy.Zone.CreateFromUrl (((HttpWebRequest)sender).RequestUri.ToString()); if (z.SecurityZone == System.Security.SecurityZone.Intranet || z.SecurityZone == System.Security.SecurityZone.MyComputer) { return true; } return false; } return true; }
我最终得到错误:
远程证书链错误
Marcelo Maso.. 10
将此问题添加到Application_Start可以解决此问题:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
它基本上允许服务器与其证书不匹配.
资源:
http://www.ben-morris.com/asp-net-web-services-and-ssl-certificates-establishing-a-trust-relationship
注意:建议不要将此解决方法用于生产
将此问题添加到Application_Start可以解决此问题:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
它基本上允许服务器与其证书不匹配.
资源:
http://www.ben-morris.com/asp-net-web-services-and-ssl-certificates-establishing-a-trust-relationship
注意:建议不要将此解决方法用于生产