阿不

潜水

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

在.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://blog.joycode.com/mvm/archive/2006/03/25/734...

http://blog.jerrysherman.com/PermaLink,guid,c26899...

阿不 http://hjf1223.cnblogs.com
posted on 2007-03-14 13:47  阿不  阅读(9951)  评论(7编辑  收藏  举报