在WCF 3.0中获取客户端IP地址

时间:2020-03-06 14:21:40  来源:igfitidea点击:

显然,我们可以在WCF 3.5中轻松获得客户端IP地址,而在WCF 3.0中则不能。有人知道吗?

解决方案

在3.0中这对我们没有帮助,但是我只能看到人们发现此问题并感到沮丧,因为他们试图在3.5中获得客户端IP地址。因此,这是一些应该起作用的代码:

using System.ServiceModel;
using System.ServiceModel.Channels;

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
    prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

事实证明,只要(a)将服务托管在Web服务中(显然),并且(b)启用AspNetCompatibility模式,就可以做到,如下所示:

<system.serviceModel>
            <!-- this enables WCF services to access ASP.Net http context -->
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
...
    </system.serviceModel>

然后,我们可以通过以下方式获取IP地址:

HttpContext.Current.Request.UserHostAddress

如果我们以.NET 3.0 SP1为目标,则可以。

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

学分:
http://blogs.msdn.com/phenning/archive/2007/08/08/remoteendpointmessageproperty-in-wcf-net-3-5.aspx

参考:
http://msdn.microsoft.com/zh-CN/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx