从 WebApi 调用 WCF 服务抛出 MessageSecurityException

Calling WCF service from WebApi throws MessageSecurityException

我使用第 3 方客户端库,它使用 WCF 与服务器(在云中的某处)进行内部通信(我只能配置很少的 key/value 设置,该库在其代码中创建所有 WCF 客户端代理堆栈)。

如果我在 WinForms 或控制台应用程序中使用该库,它运行良好,但是从 WebApi 中调用该库 API 它最终会出现错误:

An exception of type 'System.ServiceModel.Security.MessageSecurityException' occurred in mscorlib.dll but was not handled in user code

Additional information: The Identity check failed for the outgoing message. 
The remote endpoint did not provide a domain name system (DNS) claim and therefore did not satisfied DNS identity 'serverName'. 
This may be caused by lack of DNS or CN name in the remote endpoint X.509 certificate's distinguished name.

为什么会有差异?服务器端是一样的,那么这是否意味着在 WinForms 应用程序中 运行ning 时不执行身份检查?或者在 WebApi 中 运行ning 时身份检查的执行方式不同?我该如何解决?

我 运行 VS2015 中的代码,WebApi 托管在 IISExpress 中。该库使用 NetTcpBindingTransportWithMessageCredentialMessageCredentialType.UserName

尝试将此添加到您的 app.config 文件

<configuration>
    <runtime>
        <AppContextSwitchOverrides value="Switch.System.IdentityModel.DisableMultipleDNSEntriesInSANCertificate=true" />
    </runtime>
</configuration>

来自 MSDN:

Starting with apps that target the .NET Framework 4.6.1, the X509CertificateClaimSet.FindClaims method will attempt to match the claimType argument with all the DNS entires in its SAN field. Impact

This change only affects apps that target the .NET Framework 4.6.1.

For apps that target previous versions of the .NET Framework, the X509CertificateClaimSet.FindClaims method attempts to match the claimType argument only with the last the DNS entry. Mitigation

If this change is undesirable, apps that target the .NET Framework 4.6.1 can opt out of it by adding the following configuration setting to the section of the app’s configuration file:

https://msdn.microsoft.com/en-us/library/mt620030%28v=vs.110%29.aspx