在负载均衡的情况下使用WCF 4.5 RemoteEndpointMessageProperty获取客户端IP地址
本文关键字:RemoteEndpointMessageProperty 获取 客户端 地址 IP WCF 负载 情况下 | 更新日期: 2023-09-27 18:18:02
我在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客户端吗?
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。
最重要的是如果你使用
async await
OperationContext.Current; will be null
我的用法是获取Ip,所以在任何可等待调用
之前使用它var clientIpAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;
在异步服务操作的第一个await语句之后,OperationContext。Current可以为空,因为方法体的其余部分可能在不同的线程上运行(并且OperationContext不会在线程之间流动
)。因此,为了获得它,您可以在任何可等待操作之前编写代码
也许能帮到别人