我有下面的代碼片段,我是從一組集成測試呼叫:爲什麼設置ServicePointManager.ServerCertificateValidationCallback = null不起作用?
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); };
我不能讓Web客戶端在同一個試運行再次拋出一個證書錯誤,即使我明確地指定此委託爲null。我也嘗試明確返回false;我嘗試添加一個命名委託引用,然後刪除它而不是隻分配/重新分配,甚至檢查回調中的SslPolicyErrors並返回policyErrors == SslPolicyErrors.None
- 沒有任何工作。
(我明確驗證了我們的測試環境中的某些URL返回了證書警告,而且我還需要驗證如果用戶忽略了證書警告,他們將看到一個特定的頁面,因此稍微有點奇怪的證書處理)
任何想法?
將回調設置爲返回true將跳過無效證書,這是OP在後續測試中試圖避免的內容。另外,賦值運算符是單個等於。 –