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

时间:2015-10-16 09:16:33

标签: c# asp.net wcf load-balancing wcf-rest

我在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 客户端?

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:0)

最重要的是,如果您使用的是

async await 
OperationContext.Current; will be null

我的用法是在等待呼叫之前让Ip如此使用

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

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

因此,要获取它,您可以在任何等待的操作之前编写代码

也许会帮助某人:)