在负载平衡情况下使用WCF 4.5 RemoteEndpointMessageProperty获取客户端IP地址

问题描述 投票:5回答:2

我在IIS中托管了WCF 4.5 Restful服务,我正在尝试使用RemoteEndpointMessageProperty来获取使用该服务的客户端的IP地址。

代码1:

private string GetClientIP()
{
  OperationContext context = OperationContext.Current;
  MessageProperties prop = context.IncomingMessageProperties;
  RemoteEndpointMessageProperty endpoint =
         prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
  string ip = endpoint.Address;
  return ip;
}

代码2:

private string GetClientIP()
{
  string retIp = string.Empty;
  OperationContext context = OperationContext.Current;
  MessageProperties prop = context.IncomingMessageProperties;
  HttpRequestMessageProperty endpointLoadBalancer =
  prop[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
  if (endpointLoadBalancer.Headers["X-Forwarded-For"] != null)
  {
    retIp = endpointLoadBalancer.Headers["X-Forwarded-For"];
  }
  if (string.IsNullOrEmpty(retIp))
  {
    RemoteEndpointMessageProperty endpoint =
                prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                retIp = endpoint.Address;
  }
  return retIp;
}

但是,由于WCF服务托管在负载均衡器后面的IIS中,因此我获得的IP地址始终是负载均衡器的IP。有没有办法解决这个问题,以便我可以获得客户的真正IP?

c# asp.net wcf load-balancing wcf-rest
2个回答
19
投票
OperationContext context = OperationContext.Current;
MessageProperties properties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string address = string.Empty;
//http://www.simosh.com/article/ddbggghj-get-client-ip-address-using-wcf-4-5-remoteendpointmessageproperty-in-load-balanc.html
if (properties.Keys.Contains(HttpRequestMessageProperty.Name))
{
    HttpRequestMessageProperty endpointLoadBalancer = properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
    if (endpointLoadBalancer != null && endpointLoadBalancer.Headers["X-Forwarded-For"] != null)
        address = endpointLoadBalancer.Headers["X-Forwarded-For"];
}
if (string.IsNullOrEmpty(address))
{
    address = endpoint.Address;
}

这适用于负载均衡器,也没有负载均衡器。我有一个端点作为TCP,另一个端点作为REST API的web http。


0
投票

最重要的是如果你正在使用

async await 
OperationContext.Current; will be null

我的用法是让Ip在任何等待通话之前就这样使用它

var clientIpAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;

在异步服务操作中的第一个await语句之后,OperationContext.Current可能为null,因为方法体的其余部分可能在不同的线程上运行(并且OperationContext不在线程之间流动

因此,为了得到它,您可以在任何可行的操作之前编写代码

可能它会帮助别人:)

© www.soinside.com 2019 - 2024. All rights reserved.