我目前有一个RESTful C#web服务来获取客户端的IP地址。这工作正常,直到实现负载平衡。所以,现在Web服务正坐在负载平衡器后面。在C#中获取IP地址
现在,每次我尝试获取用户的IP地址时,我都会获取负载平衡器的IP地址。这里是代码的样子...
System.Web.HttpContext context = System.Web.HttpContext.Current;
if (context.Request.ServerVariables.AllKeys.Contains("HTTP_CLIENT_IP") && CheckIP(context.Request.ServerVariables["HTTP_CLIENT_IP"]))
return new Model(context.Request.ServerVariables["HTTP_CLIENT_IP"]);
if (context.Request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED_FOR"))
foreach (string ip in context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(','))
if (CheckIP(ip.Trim()))
return new Model(ip.Trim());
if (context.Request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED") && CheckIP(context.Request.ServerVariables["HTTP_X_FORWARDED"]))
return new Model(context.Request.ServerVariables["HTTP_X_FORWARDED"]);
if (context.Request.ServerVariables.AllKeys.Contains("HTTP_X_CLUSTER_CLIENT_IP") && CheckIP(context.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"]))
return new Model(context.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"]);
if (context.Request.ServerVariables.AllKeys.Contains("HTTP_FORWARDED_FOR") && CheckIP(context.Request.ServerVariables["HTTP_FORWARDED_FOR"]))
return new Model(context.Request.ServerVariables["HTTP_FORWARDED_FOR"]);
if (context.Request.ServerVariables.AllKeys.Contains("HTTP_FORWARDED") && CheckIP(context.Request.ServerVariables["HTTP_FORWARDED"]))
return new Model(context.Request.ServerVariables["HTTP_FORWARDED"]);
return new Model(context.Request.ServerVariables["REMOTE_ADDR"]);
尽管如此,我仍然最终得到错误的IP地址。有什么想法吗?想法?我错过了什么吗?
你可以在未来的原始请求的痕迹?如果是这样,是否有任何标题包含原始IP地址?如果没有,你需要改变你的负载平衡器给你这个数据,否则你运气不好。如果是这样,只需要请求该头并获取数据。 – Tejs
尝试HTTP标头的'X-Forwarded-For'。 – vcsjones