0

我在负载平衡服务器上有 MVC 应用程序,我想设置真实客户端的 IP 地址。我在自定义标头上添加了“X-Forwarded-For”,并使用下面的 c#.net 代码获取 IP 地址,但它返回 null。请帮助我如何检查或如何做。谢谢你。

添加自定义标题:

Response.AddHeader("X-Forwarded-For", "client1, proxy1, proxy2");

c#.net 代码:

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;
4

0 回答 0