在.NET调用加了SSL验证的WebService可让我费了不少心思。要使用SSL证书加密,必须要根据证书创建X509Certificate实例,添加到WebService实例的ClientCertificates集合属性中:
string certificateFile = AppDomain.CurrentDomain.BaseDirectory + @"\certificate.cer"; System.Security.Cryptography.X509Certificates.X509Certificate certificate = System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(certificateFile); creatinoService.ClientCertificates.Add(certificate);
但是我这里,调用却会提示出现:The remote certificate is invalid according to the validation procedure.异常,它的内部异常是WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel。通过网络资源找到了解决方案:
using System.Net; using System.Security.Cryptography.X509Certificates; public class MyPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint , X509Certificate certificate , WebRequest request , int certificateProblem) { //Return True to force the certificate to be accepted. return true; } // end CheckValidationResult } // class MyPolicy System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
通过上面的代码,马上就解决了我的问题。
但是由于是使用.NET 2.0,它会提示你CertificatePolicy 属性已经过期了,我们可以使用下面的回调方式来替代它:
System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);
增加一个静态回调函数:
public static bool RemoteCertificateValidationCallback( Object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors ) { //Return True to force the certificate to be accepted. return true; }
你会发现,这样同样也能解决这个问题。
相关文章:
阿不 http://hjf1223.cnblogs.com