首页 文章

在.Net中调用Web服务时,绕过无效的SSL证书错误

提问于
浏览
82

我们正在设置一个新的SharePoint,但我们还没有有效的SSL证书 . 我想在其上调用Lists Web服务来检索有关设置的一些元数据 . 但是,当我尝试这样做时,我得到了例外:

基础连接已关闭:无法为SSL / TLS安全通道 Build 信任关系 .

嵌套异常包含错误消息:

根据验证程序,远程证书无效 .

这是正确的,因为我们使用的是临时证书 .

我的问题是:如何告诉.Net Web服务客户端(SoapHttpClientProtocol)忽略这些错误?

8 回答

  • 21

    我遇到此问题时使用的方法是将临时证书的签名者添加到相关计算机上的受信任机构列表中 .

    我通常使用CACERT创建的证书进行测试,并将它们添加到我信任的权限列表中 .

    这样做意味着您不必向应用程序添加任何自定义代码,它可以正确模拟部署应用程序时会发生的情况 . 因此,我认为这是以编程方式关闭检查的优秀解决方案 .

  • 73

    或者,您可以注册一个忽略认证错误的回叫代理:

    ...
    ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
    ...
    
    static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
    {
    // Ignore errors
    return true;
    }
    
  • 2

    就像Jason S的回答一样:

    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    

    我把它放在我的Main中并查看我的 app.config 并在调用该行代码之前测试 (ConfigurationManager.AppSettings["IgnoreSSLCertificates"] == "True") .

  • 110

    我这样解决了:

    在调用导致该错误的ssl webservice之前调用以下内容:

    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    
    /// <summary>
    /// solution for exception
    /// System.Net.WebException: 
    /// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
    /// </summary>
    public static void BypassCertificateError()
    {
        ServicePointManager.ServerCertificateValidationCallback +=
    
            delegate(
                Object sender1,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
    }
    
  • 10

    我使用DownloadString时遇到了同样的错误;并能够使其工作如下,并在此页面上提出建议

    System.Net.WebClient client = new System.Net.WebClient();            
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    string sHttpResonse = client.DownloadString(sUrl);
    
  • 1
    ServicePointManager.ServerCertificateValidationCallback +=
                (mender, certificate, chain, sslPolicyErrors) => true;
    

    将绕过invaild ssl . 将其写入您的Web服务构造函数 .

  • 1

    对于新手,您可以在单独的cs文件中扩展您的部分服务类,并添加“imanabidi”提供的代码以使其集成

  • 17

    进一步扩展Simon Johnsons的帖子 - 理想情况下,你想要一个能够模拟你在 生产环境 中看到的条件并修改你的代码的解决方案将不会这样做,如果你在部署代码之前忘记了代码,那么可能会很危险 .

    您需要某种自签名证书 . 如果你正在使用IIS Express,你将拥有其中一个,你只需要找到它 . 打开Firefox或您喜欢的任何浏览器,然后转到您的开发网站 . 您应该能够从URL栏查看证书信息,并且根据您的浏览器,您应该能够将证书导出到文件中 .

    接下来,打开MMC.exe,然后添加“证书”管理单元 . 将您的证书文件导入受信任的根证书颁发机构商店,这就是您应该需要的 . 重要的是要确保它进入该商店,而不是像“个人”这样的其他商店 . 如果您不熟悉MMC或证书,那么有许多网站都会提供有关如何执行此操作的信息 .

    现在,您的计算机作为一个整体将隐式信任它自己生成的任何证书,您不需要添加代码来专门处理它 . 当您转到 生产环境 时,如果您在那里安装了正确的有效证书,它将继续工作 . 不要在 生产环境 服务器上执行此操作 - 这样做会很糟糕,除了服务器本身以外的任何其他客户端都不会 .

相关问题