我在负载均衡服务器上有MVC应用程序,我想设置真实客户端的IP地址。我在自定义标头上添加了“X-Forwarded-For”,并使用如下的c#.net代码获取IP地址,但它返回null。请帮助我如何检查或如何做。谢谢。
添加自定义标题:
Response.AddHeader("X-Forwarded-For", "client1, proxy1, proxy2");
c#.net code:
string IP_REMOTE_ADDR = string.Empty;
string IP_HTTP_X_FORWARDED_FOR = string.Empty;
string RETURN_IP = string.Empty;
IP_REMOTE_ADDR = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]) ? "" : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
IP_HTTP_X_FORWARDED_FOR = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? "" : System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (IP_HTTP_X_FORWARDED_FOR != "")
{
RETURN_IP = IP_HTTP_X_FORWARDED_FOR;
if (RETURN_IP.Contains(","))
{
RETURN_IP = RETURN_IP.Split(',')[0];
}
}
else
{
if(IP_REMOTE_ADDR != "")
{
RETURN_IP = IP_REMOTE_ADDR;
}
else
{
RETURN_IP = "";
}
}
return RETURN_IP;