Get Client IP address using WCF 4.5 RemoteEndpointMessageProperty in load balancing situation

ぐ巨炮叔叔 提交于 2019-12-04 08:47:15
Mahesh Malpani
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;
}

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.

Most Important thing is if you're using

async await 
OperationContext.Current; will be null

My usage is to get Ip so used it like this before any awaitable call

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

After the first await statement in your async service operation, OperationContext.Current could be null because the rest of the method body may be running on a different thread (and OperationContext does not flow between threads

So to get it you can write your code before any awaitable action

May be it'll help someone :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!