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

Gaz*_*Gaz 82 wcf

显然,您可以轻松地在WCF 3.5中获取客户端IP地址,但不能在WCF 3.0中获取.谁知道怎么样?

Pau*_*ski 152

这对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;
Run Code Online (Sandbox Code Playgroud)

  • 我无法编辑帖子,但它帮了我一吨,谢谢!想提一下有2个错误.应该是"OperationContext"而不是"OperationContent",应该是"RemoteEndpointMessageProperty"而不是"RemoveEndpointMessageProperty". (11认同)
  • 安全说明:此值可能是欺骗性的...请参阅MSDN (3认同)

Gaz*_*Gaz 36

事实证明,只要(a)您的服务托管在Web服务中(显然)和(b)您启用AspNetCompatibility模式,如下所示:

    <system.serviceModel>
            <!-- this enables WCF services to access ASP.Net http context -->
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
...
    </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

然后你可以通过以下方式获得IP地址:

HttpContext.Current.Request.UserHostAddress
Run Code Online (Sandbox Code Playgroud)

  • 然后你通过使用`HttpContext.Current.Request.UserHostAddress`得到它 (11认同)
  • 请注意,这会引发一系列问题 (3认同)

小智 15

如果您的目标是.NET 3.0 SP1,则可以.

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 好吧,我看起来像获得像"fe80 :: 3dbc:a2ec"这样的IPv6.我在徘徊,我怎么能得到远程IP号码 (3认同)