2014-01-24 169 views
9

我正在一个WinForms应用程序中的Web请求。我提供定制证书验证,像这样:为什么我的ServicePointManager.ServerCertificateValidationCallback被忽略?

ServicePointManager.ServerCertificateValidationCallback += 
     new RemoteCertificateValidationCallback(certValidator.ValidateRemoteCertificate); 

其中certValidator.ValidateRemoteCertificate是

public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, 
             X509Chain chain, SslPolicyErrors policyErrors) 
{ 
     return false; 
} 

正如你所看到的,这个回调应该拒绝所有服务器证书并关闭所有连接尝试。

我的问题是,这个回调是完全忽略。我提交一个https请求,它的功能就像一个魅力。在调试器中观察它,我可以看到ValidateRemoteCertificate从不被调用。

为什么我的替换回调从不回叫?

编辑:LB要求的WebRequest的,所以在这里它是:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceUrl); 
request.UseDefaultCredentials = true; 
request.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";  

request.KeepAlive = false; 
request.Headers.Add("Accept-Language", "en-us,en;q=1.0"); 
request.Method = "GET"; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

编辑2:这也许无关,但在config文件我指示它使用配置的代理,像这样:

<system.net> 
    <defaultProxy useDefaultCredentials="true"/> 
</system.net> 

编辑3:下面是一个完整的,最小的例子,体现了行为。我期望这个例子抛出一个异常,因为所有的证书都应该被拒绝,但它工作得很好。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Text; 

namespace SPMCertCallbackDemonstrator 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ServicePointManager.ServerCertificateValidationCallback = delegate { return false;}; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com"); 
      request.Method = "GET"; 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     } 
    } 
} 

为什么我的替换回调从不回叫?

+0

'我提交一个https请求,它的工作原理就像一个魅力。“代码在哪里? –

+0

编辑为包含https请求代码。 – Eric

+0

你在什么时候注册验证回调?在应用程序启动或...? –

回答

4

我发布的原始代码没有错。我通过http而不是https请求。因此不需要证书验证。只要我调用https请求,它就可以正常工作。