Error: C# The underlying connection was closed: Co

2019-03-17 12:47发布

问题:

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

I am using this request:

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:

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.

What is the problem?

回答1:

I solved the problem with this:

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


回答2:

Make sure your certificate is properly trusted. Has the root certificate been added to the correct certificate store (Trusted Root CA's on Local Machine)?

I encountered this error when the (own made) root certificate for a (self signed) certificate had been added to the Trusted Root CA's for Current User). Moving the root cert to the Root CA store on Local Machine solved my issue.



回答3:

This is client code, right? And you're accessing an HTTPS url, aren't you? I think the problem is with the server certificate, which the client-side TLS stack cannot validate. When you connect to that URL via browser, does it work smoothly or do you see a warning on certificate mismatch?