通过X-Forwarded-For从负载均衡服务器获取客户端的IP地址

时间:2017-10-18 04:16:57

标签: c# asp.net-mvc load-balancing x-forwarded-for

我在负载均衡服务器上有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;

0 个答案:

没有答案