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

82

据说在WCF 3.5中可以很容易地获得客户端IP地址,但在WCF 3.0中不行。有人知道怎么做吗?

3个回答

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;

11
我无法编辑这篇文章,但它对我帮助很大,谢谢!想提一下有两个错误。应该是"OperationContext"而不是"OperationContent",还应该是"RemoteEndpointMessageProperty"而不是"RemoveEndpointMessageProperty"。 - Jeremy Mullin
3
安全提示:此值可能被伪造...请参阅MSDN。 - makerofthings7
1
@cost 在这种情况下,“IP”不仅存在于TCP数据包中,而且还驻留在WCF消息中,但是数据流(第7层)中的文本未得到适当的安全保护。 - makerofthings7
1
@shambulator 自从我看到这个问题已经过去了几年,但是以下 KB 文章似乎表明可能是端口而不是 IP 地址的问题。http://support.microsoft.com/kb/971842 - makerofthings7
如果你获取 OperationContext.Current 时第一行返回 null,那么你目前遇到的问题是什么?你可以怎么做? - Franck
显示剩余4条评论

36

事实证明,只要(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

11
然后,您可以通过使用HttpContext.Current.Request.UserHostAddress来获得它。 - Jader Dias
3
注意,这会引发一系列问题。 - user1496062

16

如果你的目标是 .NET 3.0 SP1,那么是可以的。

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

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

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


3
好的,看起来我得到了一个IPv6地址,类似于“fe80 :: 3dbc:a2ec”。我在想如何获取远程IP地址。 - Junior Mayhé
@makerofthings7 在做安全决策时,我们应该使用什么? - M. Jahedbozorgan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接