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

问题描述:

我正在尝试通过SSL发出请求。证书已经安装在计算机上,并且可以通过浏览器运行。

I'm trying to make a request via SSL. The certificate is already installed on the machine and it works via browser.

我正在使用此请求:

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());

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

Using this code I get this error:

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

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

出什么问题了?

我用以下方法解决了这个问题:

I solved the problem with this:

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