When I write a program today, I call a third-party DLL file. The local debugging is normal, but the program does not always prompt a BUG after it arrives at the server: "The basic connection has been closed: failed to establish trust relationship for SSL/TLS Security Channel ".
Later, the DLL file was decompiled and an error occurred while obtaining the request. Reference WebResponse response = WebRequest. Create ("https ://...... "). GetResponse ();
Then, open the above address in the browser on the server and a confirmation certificate window will pop up, which seems to be a certificate problem.
After a search on the Internet, I found that it is easy to use and add a line of code before the request. C # code
- ServicePointManager. CertificatePolicy = new AcceptAllCertificatePolicy ();
ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
The AcceptAllCertificatePolicy must be defined by yourself: C # code
- Internal class AcceptAllCertificatePolicy: ICertificatePolicy
- {
- Public AcceptAllCertificatePolicy ()
- {
- }
- Public bool CheckValidationResult (ServicePoint sPoint,
- X509Certificate cert, WebRequest wRequest, int certProb)
- {
- // Always accept
- Return true;
- }
- }
internal class AcceptAllCertificatePolicy : ICertificatePolicy { public AcceptAllCertificatePolicy() { } public bool CheckValidationResult(ServicePoint sPoint, X509Certificate cert, WebRequest wRequest, int certProb) { // Always accept return true; } }
The preceding method solves the problem, but in VS, it will prompt that ServicePointManager. CertificatePolicy has been rejected. As I like perfection, follow the prompts to use a new method.
The transformed code is more concise and clear C # code
- ServicePointManager. ServerCertificateValidationCallback = ValidateServerCertificate;
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
C # code
- Private bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
- {
- Return true;
- }
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }
That's it! A commission is done!
From: http://radiumwong.iteye.com/blog/684118