Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am currently integrating with a system created by a 3rd party. This system requires me to send a request using XML/HTTPS. The 3rd party send me the certificate and I installed it

I use the following code:

using (WebClient client = new WebClient())
{
   client.Headers.Add(HttpRequestHeader.ContentType, "text/xml");

   System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
   var response = client.UploadData(address, "POST", encoding.GetBytes(msg));
}

This code returns the following WebException:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

UPDATE Because it's a test server I am working against, the certificate isn't trusted and validation fails... To bypass this in test/debug environment, create a new ServerCertificateValidationCallback

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);

and here is my "fake" callback

private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
   return true;
}

Read more here and here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
393 views
Welcome To Ask or Share your Answers For Others

1 Answer

The shortest notation of the code to allow all certificates is actually:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

And works well for this error. Needless to say that you should provide an implementation which actually checks the certificate and decides based on the certificate information if the communication is safe. For test purposes, use the above line of code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...