Web Service via SSL
如果你调用一个启用了SSL的Web服务,你会收到如下错误:
"The underlying connection was closed: Could not establish trust relationship with remote server."
这是因为客户端没有接受服务端证书,在添加服务的时候,有个提示框出来让你确认证书,但是在程序调用时是没有办法去选择的,那么我们可以创建一个证书策略来解决这个问题。
System.Net.ICertificatePolicy接口定义了自定义证书验证策略,我们就实现这个接口,然后实现自己的CheckValidationResult方法就可以了。对了,没那么复杂的,看代码:
Code
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{}
public bool CheckValidationResult(ServicePoint sp,
X509Certificate cert,WebRequest req, int problem)
{
return true;
}
}
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{}
public bool CheckValidationResult(ServicePoint sp,
X509Certificate cert,WebRequest req, int problem)
{
return true;
}
}
对的,return true就可以了。
我们在创建Web Service的代理类实例前,创建我们自己的证书验证策略类就好了:
Code
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
然后再调用Web Service的方法就没有问题了。
from here.