忽略 ASP.NET Core 3.1 中的 WCF 证书错误

Ignore WCF certificate errors in ASP.NET Core 3.1

我有这样的解决方案:

-MySolution
|--MyWCFWrapper
|--MyaspnetcoreWebApp
|--ConsoleTestApp

MyWCFWrapper 是一个 .NET Standard 库,它使用使用 Visual Studio 导入向导添加为 WCF 引用的 WCF 服务。

MyaspnetcoreWebApp 应用程序提供控制器供前端使用。在这个控制器中,我正在实例化并调用 MyWCFWrapper 库。

ConsoleTestApp 是一个控制台应用程序,它也会调用 MyWCFWrapper 库进行测试。

我收到一个错误:

System.ServiceModel.Security.SecurityNegotiationException: 'Could not establish trust relationship for the SSL/TLS secure channel with authority 'exampleabc.com'

当我进行 WCF 服务调用时。

此错误的原因是我在 exampleablc.com 的 WCF 服务是一个测试服务器并且有一个自签名证书(名称与 web 服务不同)并且也是 过期.

适用于 ConsoleTestApp 的解决方法:

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
    (se, cert, chain, sslerror) =>
    {
        return true;
    };
MyWCFWrapperClass api = new MyWCFWrapperClass(..);
api.SendNewInfo("NewInfo");

不推荐,但目前对我来说还可以,因为它是测试服务器。

相同的解决方法在 MyaspnetcoreWebApp 控制器中不起作用。我努力让它发挥作用:.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient("SeitaCertificate").ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
            ServerCertificateCustomValidationCallback = (request, certificate, certificateChain, policy) =>
            {
                return true;
            }
        };
    });
    services.AddControllersWithViews();
    ----
}

WCF 调用库中出现了证书错误,我无法找到忽略证书错误的方法。 我能做的是至少更新证书,使其不会过期。 (我已经开始这个过程,可能需要一些时间)

我想了解如何有选择地适当地捕获和忽略这些证书错误,以便在 asp .net core 3.1 Web 应用程序中调用 WCF 库。我该怎么做?

您可以参考以下代码绕过证书验证:

            BasicHttpsBinding binding = new BasicHttpsBinding();
            binding.Security.Mode = BasicHttpsSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, new EndpointAddress(uri));

            factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new System.ServiceModel.Security.X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None,
                RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
            };