在负载平衡情况下使用WCF 4.5 RemoteEndpointMessageProperty获取客户端IP地址 [英] Get Client IP address using WCF 4.5 RemoteEndpointMessageProperty in load balancing situation
问题描述
我已经在IIS中托管了WCF 4.5 Restful服务,我正在尝试使用 RemoteEndpointMessageProperty来获取谁的客户端的IP地址 使用服务.
I have hosted WCF 4.5 Restful service in IIS and I am trying to use RemoteEndpointMessageProperty to get the IP address of the client who consumes the service.
代码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. 有什么办法可以解决这个问题,以便我可以获取 客户?
However, since the WCF service is hosted in IIS behind a load balancer, the IP address I got is always the IP of the load balancer. Is there any way to get around this so that I can get the true IP of the client?
推荐答案
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;
}
这在负载均衡器的情况下有效,在没有负载均衡器的情况下也是如此.对于REST API,我有一个端点为TCP,另一个为web http.
This works in case of load balancer and without it also. I had one endpoint as TCP and other one as web http for REST API.
这篇关于在负载平衡情况下使用WCF 4.5 RemoteEndpointMessageProperty获取客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!