使用 BasicHttpBinding 和 Windows 身份验证使用 WCF 服务

Mic*_*ill 6 .net wcf

我有一个具有以下绑定的 WCF 服务:

<basicHttpBinding>        
  <binding name="bind" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
     <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
        <message algorithmSuite="Default" clientCredentialType="UserName"/>
     </security>
  </binding>
</basicHttpBinding>
Run Code Online (Sandbox Code Playgroud)

我通过此端点在代码中动态使用它:

BasicHttpBinding binding = new BasicHttpBinding();
binding.Name = "bind";
binding.MaxBufferSize = int.MaxValue;
binding.MaxReceivedMessageSize = int.MaxValue;
ServiceEndpoint endPoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(ImyContract)), binding, new EndpointAddress(endPointAddress));

endPoint.Name = name;
ChannelFactory<ImyContract> channelFactory = new ChannelFactory<ImyContract>(endPoint);
Run Code Online (Sandbox Code Playgroud)

当我浏览到该服务时,一切都完全按预期工作,但是当通过应用程序连接时,我得到:

内容类型文本/xml;服务 http://localhost/SynchronizationService/SyncService.svc/DataBinding不支持 charset=utf-8 。客户端和服务绑定可能不匹配。

我知道这个错误通常是因为 basicHttpBinding 使用 SOAP 1.1 和 wsHttpBinding 使用 1.2 引起的,但是,我没有在服务器上使用 SSL,并且有另一个使用流的端点,所以切换对我来说不是一个选择。我做错了什么导致我无法正确使用服务?

更新:

另外,我没有在客户端上使用默认的 basicHttpBinding,而是设置安全性以匹配服务器的期望。我用这种方法设置安全性:

private static BasicHttpSecurity SetEndpointSecurity()
{
    BasicHttpSecurity security = new BasicHttpSecurity();
    HttpTransportSecurity transport = new HttpTransportSecurity();
    BasicHttpMessageSecurity message = new BasicHttpMessageSecurity();

    security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;

    transport.ClientCredentialType = HttpClientCredentialType.Windows;
    transport.ProxyCredentialType = HttpProxyCredentialType.None;
    transport.Realm = "";

    message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
    message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;

    security.Transport = transport;
    security.Message = message;

    return security;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ill 1

感谢 the_ajp 您的建议,让 .NET 构建代理类,然后在代码中重新实现其端点,因为这使我找到了正确的解决方案!

事实证明,我尝试解决错误“客户端和服务绑定可能不匹配”,导致我使客户端和服务器端点绑定过于相似。关键是在客户端端点上将 TextEncoding 显式指定为 UTF-8 并在客户端上使用 wsHttpBinding,即使我连接到服务器上的 basicHttpBinding 也是如此。这使得消息从源到目的地一直保持在 SOAP 1.2 中,无需在服务器上设置 SSL 安全性。

感谢你们为找到正确的解决方案提供的所有帮助!

Kris C,希望这对您接下来的工作有用:)!