错误:C#底层连接已关闭:无法为SSL / TLS安全通道建立信任关系

时间:2012-06-27 09:01:45

标签: c# ssl httpwebrequest certificate put

我正在尝试通过SSL发出请求。证书已经安装在机器上,可以通过浏览器工作。

我正在使用此请求:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] data = encoding.GetBytes(request.Content.OuterXml.ToString());
string password = "XXXX";
X509Certificate2 cert = new X509Certificate2("c:\\zzzz.p12", password);
string key = cert.GetPublicKeyString();
string certData = Encoding.ASCII.GetString(cert.Export(X509ContentType.Cert));

Uri uri = new Uri(request.Url);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);
myRequest.Credentials = new NetworkCredential(request.User, request.Password.ToString());
myRequest.Method = "PUT";
myRequest.ContentType = request.ContentType;
myRequest.ContentLength = data.Length;
myRequest.ClientCertificates.Add(cert);

Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();

System.IO.StreamReader st = new StreamReader(((HttpWebResponse)myRequest.GetResponse()).GetResponseStream());

使用此代码我收到此错误:

  

基础连接已关闭:无法建立信任   SSL / TLS安全通道的关系。 --->   System.Security.Authentication.AuthenticationException:远程   证书根据验证程序无效。

有什么问题?

3 个答案:

答案 0 :(得分:64)

我解决了这个问题:

ServicePointManager.ServerCertificateValidationCallback = new        
RemoteCertificateValidationCallback
(
   delegate { return true; }
);

答案 1 :(得分:0)

确保您的证书得到正确信任。是否已将根证书添加到正确的证书存储区(本地计算机上的受信任的根CA)?

当(自签名)证书的(自己制作的)根证书已添加到当前用户的受信任根CA时,我遇到此错误。将根证书移动到Local Machine上的根CA存储解决了我的问题。

答案 2 :(得分:-2)

这是客户端代码,对吗?你正在访问HTTPS网址,不是吗? 我认为问题在于服务器证书,客户端TLS堆栈无法验证。 当您通过浏览器连接到该URL时,它是否能够顺利运行,或者您是否看到证书不匹配的警告?