临时禁用证​​书验证

时间:2014-10-14 13:21:18

标签: c# certificate

我需要使用Web服务,但它有证书,我需要禁用其身份验证。

服务器端可以是虚拟服务器,我们正在使用它来模拟"结果或使用安全肥皂标题的真正的第三方服务器

我需要能够在调用虚拟服务器时禁用服务器中的证书验证,但是在调用真实服务器(不是我们的服务器)时启用它

我在一些帖子中看到禁用它的方法是这样做:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

完美无缺。

问题是,一旦执行了这行代码,我似乎无法反转"它

我需要类似的东西:

if (TestMode)
{
  ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
else
{
  //enable certificate validation
}

顺便说一下,代码在c#中。

任何想法?

1 个答案:

答案 0 :(得分:3)

您需要取消注册回调,如下所示:

声明RemoteCertificateValidationCallback引用。

    static RemoteCertificateValidationCallback _callbackTrue;

然后在初始化代码中,像这样分配:

    _callbackTrue = (sender, cert, chain, sslPolicyErrors) => true;

然后,当TestMode属性发生更改时,您可以注册/取消注册回调:

  // in the setter for TestMode, when set to true. 
  ServicePointManager.ServerCertificateValidationCallback += _callbackTrue;

  // in the setter for TestMode, when set to false
  ServicePointManager.ServerCertificateValidationCallback -= _callbackTrue;

当TestMode从' false变为true时,请确保只注册然后回调#39;并且只有当回调从“真”变为“假”时才会取消注册回调。即您的注册/注销应该是对称的。