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

时间:2020-03-06 14:29:30  来源:igfitidea点击:

我们正在设置一个新的SharePoint,但我们尚未为其提供有效的SSL证书。我想在其上调用Lists Web服务以检索有关该设置的一些元数据。但是,当我尝试执行此操作时,出现异常:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

嵌套异常包含错误消息:

The remote certificate is invalid according to the validation procedure.

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

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

解决方案

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

我通常会使用CACERT创建的证书进行测试,并将其添加到我信任的授权机构列表中的过程非常顺利。

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

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

...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...

static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}

就像Jason S的答案一样:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

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

我是这样解决的:

在调用导致该错误的ssl网络服务之前,请调用以下命令:

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;
        };
}