string requestClientIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(requestClientIpAddress)) requestClientIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (string.IsNullOrEmpty(requestClientIpAddress)) requestClientIpAddress = HttpContext.Current.Request.UserHostAddress;
經過測試 存在負載均衡的時候 ,HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 取出的是真實的客戶端 IP地址 ,而HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] 和 HttpContext.Current.Request.UserHostAddress 取出的是被分配的保留地址
注:X-Forwarded-For:簡稱XFF頭,它代表代表客戶端,也就是HTTP的請求端真實的IP,只有在通過了HTTP 代理或者負載均衡服務器時才會添加該項