我目前有一個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