1

我有以下片段,我从一组集成测试中调用:

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 返回证书警告,并且我还需要验证如果用户忽略证书警告,他们将看到特定页面,因此证书处理有点奇怪)

有任何想法吗?

4

2 回答 2

2

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

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

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

于 2012-10-17T19:14:15.260 回答
0

你应该打电话——

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

在创建请求之前,在您的情况下,在调用之前

var wc = new WebClient();
于 2015-01-08T22:55:59.950 回答