SSL通信-忽略证书认证错误
.NET的SSL通信过程中,使用的证书可能存在各种问题,某种情况下可以忽略证书的错误继续访问。可以用下面的方式跳过服务器证书验证,完成正常通信。
1.设置回调属性ServicePointManager.ServerCertificateValidationCallback
注:这个属性设置为要用于客户端的服务器证书的自定义验证方法
True:认证成功; False:认证失败。
C#代码
1 ServicePointManager.ServerCertificateValidationCallback = 2 new RemoteCertificateValidationCallback( 3 OnRemoteCertificateValidationCallback);
VB.NET代码
1 ServicePointManager.ServerCertificateValidationCallback = _ 2 New RemoteCertificateValidationCallback( _ 3 AddressOf OnRemoteCertificateValidationCallback)
2.把证书认证函数OnRemoteCertificateValidationCallback返回值True
C#代码
1 // 忽略证书认证错误处理的函数 2 private bool OnRemoteCertificateValidationCallback( 3 Object sender, 4 X509Certificate certificate, 5 X509Chain chain, 6 SslPolicyErrors sslPolicyErrors) 7 { 8 return true; // 认证正常,没有错误 9 }
VB.NET代码
' 忽略证书认证错误处理的函数 Private Function OnRemoteCertificateValidationCallback( _ ByVal sender As Object, _ ByVal certificate As X509Certificate, _ ByVal chain As X509Chain, _ ByVal sslPolicyErrors As SslPolicyErrors _ ) As Boolean Return True ' 认证正常,没有错误
End Function