我正在尝试记录我构建的其中一个应用程序的客户端IP地址。 它在开发服务器上运行正常。 但是,只要我们将解决方案部署到具有负载均衡器的生产服务器上,它似乎就会记录Load Balancer的IP地址而不是客户端IP。
我知道我们需要添加HTTP_X_FORWARD_FOR标头。
这是我的代码:
private static string GetCurrentIp() { String clientIP = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null) ? HttpContext.Current.Request.UserHostAddress : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; return clientIP; }感谢有人能帮助我找出我所犯的错误
I am trying to log the client IP address for one of the applications that I have build. It works OK on the dev server. But as soon as we deploy the solution on to the production server, which has load balancer,it seems to log the Load Balancer's IP address rather than the client IP.
I understand that we need to add HTTP_X_FORWARD_FOR header.
This is my code :
private static string GetCurrentIp() { String clientIP = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null) ? HttpContext.Current.Request.UserHostAddress : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; return clientIP; }Appreciate if someone could help me identify the mistake that I have done
最满意答案
有时您的访问者位于代理服务器或路由器后面,标准Request.UserHostAddress仅捕获代理服务器或路由器的IP地址。 在这种情况下,用户的IP地址随后存储在服务器变量(“HTTP_X_FORWARDED_FOR”)中。
protected string GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0) { return addresses[0]; } } return context.Request.ServerVariables["REMOTE_ADDR"]; }上面的代码可以帮助你使它工作。
Sometimes your visitors are behind either a proxy server or a router and the standard Request.UserHostAddress only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").
protected string GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0) { return addresses[0]; } } return context.Request.ServerVariables["REMOTE_ADDR"]; }above code helps you to make it working.
更多推荐
发布评论