在.net4.0下WCF程序默认是不对客户端进行身份验证。而在.net3.5下WCF程序默认是对客户端进行windows身份验证。所有如果不在同一个域中.net3.5下的WCF访问会失败,报"调用方未由服务进行身份验证",因为不在同一个域中验证会失败。
现在修改配置文件然.net4.0下的WCF也进行windows身份验证,因为进行身份验证就可以获取客户端的登录名等信息。
配置文件如下
- <?xml version="1.0" encoding="utf-8"?>
- <configuration>
- <system.web>
- <authentication mode="Windows"/>
- <compilation debug="true" targetFramework="4.0" />
- </system.web>
- <system.serviceModel>
- <services>
- <service name="WcfService3.Service1" behaviorConfiguration="WcfService3.Service1Behavior">
- <!-- Service Endpoints -->
- <host>
- <baseAddresses>
- <add baseAddress="http://localhost/"/>
- </baseAddresses>
- </host>
- <endpoint address="" binding="wsHttpBinding" bindingConfiguration="userHttp" contract="WcfService3.IService1">
- <!--
- 部署时,应删除或替换下列标识元素,以反映
- 用来运行所部署服务的标识。删除之后,WCF 将
- 自动推断相应标识。
- -->
- <identity>
- <dns value="localhost"/>
- </identity>
- </endpoint>
- <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
- </service>
- </services>
- <bindings>
- <wsHttpBinding>
- <binding name="userHttp">
- <security mode="Transport">
- <transport clientCredentialType="Windows"></transport>
- </security>
- </binding>
- </wsHttpBinding>
- </bindings>
- <behaviors>
- <serviceBehaviors>
- <behavior name="WcfService3.Service1Behavior">
- <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
- <serviceMetadata httpGetEnabled="true"/>
- <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
- <serviceDebug includeExceptionDetailInFaults="true"/>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
- </system.serviceModel>
- <system.webServer>
- <modules runAllManagedModulesForAllRequests="true"/>
- </system.webServer>
- </configuration>
使用这个配置文件就出现了“WCF问题:找不到具有绑定 WSHttpBinding 的终结点的与方案 http 匹配的基址。注册的基址方案是 [https]"错误。
原因是security模型使用了Transport,如: <security mode="Transport">。Transport模型下是需要使用ssl和证书的,访问也是使用https。所有会报“注册的基址方案是 [https]"错误。只需要把安全模型修改为以下代码就可以
- <binding name="userHttp">
- <security mode="Message" >
- <message clientCredentialType="Windows"/>
- </security>
- </binding>
获取客户端信息:
- OperationContext context = OperationContext.Current;
- MessageProperties messageProperties = context.IncomingMessageProperties;
- RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
- string address = endpointProperty.Address;
- string name = ServiceSecurityContext.Current.WindowsIdentity.Name;