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

显然你可以在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; 

事实certificate,只要(a)你的服务被托pipe在一个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/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx