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

Rog*_*r G 26 c# ssl certificate put httpwebrequest

我正在尝试通过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());
Run Code Online (Sandbox Code Playgroud)

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

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

问题是什么?

Rog*_*r G 71

我解决了这个问题:

ServicePointManager.ServerCertificateValidationCallback = new        
RemoteCertificateValidationCallback
(
   delegate { return true; }
);
Run Code Online (Sandbox Code Playgroud)

  • 当您关闭SSL证书验证时,此解决方案可能是潜在的安全威胁.如果这是生产代码,请了解您要连接的服务器的风险. (20认同)
  • 我拒绝投票,因为正如@Amzath所说,这绕过了安全性。最好从根本上解决问题(双关语)。 (3认同)
  • 当我通过Fiddler汇集来自我的应用程序的请求时,问题就发生了.并且添加委托技巧以不验证证书帮助我成功运行我的调用,以及在Fiddler中查看响应. (2认同)