调用加了SSL签名的WebService

在.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 false ; }

 

你会发现,这样同样也能解决这个问题。

相关文章:

http://blog.joycode.com/mvm/archive/2006/03/25/734...

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

 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值