为什么设置ServicePointManager.ServerCertificateValidationCallback = null不起作用?

时间:2012-06-20 10:44:58

标签: c# .net ssl-certificate webclient servicepointmanager

我有以下代码片段,我正在通过一组集成测试调用:

private void Url_Contains_String_With_Certificate_Warning(string url, string expected) {
  // This line should restore default cert validation behaviour
  ServicePointManager.ServerCertificateValidationCallback = null;
  var wc = new WebClient();
  try {
    wc.DownloadString(url);
    Assert.Fail("Should have thrown a WebException by now");
  } catch (WebException x) {
    Assert.That(x.InnerException is AuthenticationException, "Expected an AuthenticationException inside a WebException due to invalid certificate");
    Assert.AreEqual("The remote certificate is invalid according to the validation procedure.", x.InnerException.Message);
  }
  // This line overrides cert validation behaviour to accept invalid certs
  ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
  var result = wc.DownloadString(url);
  Assert.That(result.Contains(expected), String.Format("Didn't find expected text '{0}' in HTML response", expected));
}

但是,只有在任何给定的测试运行中的第一个测试将通过...一旦我运行此行:

ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

我无法让WebClient在同一个测试运行中再次抛出证书错误,即使我明确地将此委托指定为null。我也试过明确地返回false;我已经尝试添加一个命名的委托引用,然后删除它而不是仅仅分配/重新分配,甚至检查回调中的SslPolicyErrors并返回policyErrors == SslPolicyErrors.None - 没有任何作用。

(我明确地验证了我们的测试环境中的某些URL返回了证书警告,我还需要验证如果用户忽略证书警告他们会看到特定页面,因此稍微奇怪的证书处理)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

将System.Net.ServicePointManager.MaxServicePointIdleTime设置为0

没有这个,连接通道保持打开状态,因此没有委托调用

http://blogs.msdn.com/b/jpsanders/archive/2009/05/20/understanding-maxservicepointidletime-and-defaultconnectionlimit.aspx

答案 1 :(得分:0)

你应该致电 -

ServicePointManager.ServerCertificateValidationCallback == delegate { return(true); };

在创建请求之前,在您调用

之前的情况下
var wc = new WebClient();