X-Forwarded-For:如何在ASP.Net MVC中获取客户端的IP地址?

时间:2015-11-16 15:13:53

标签: c# asp.net asp.net-mvc

我是asp.net mvc堆栈的新手,我想知道Request.Header对象发生了什么?

基本上我想要的是拔出设备(PC)的IP地址,但是我无法检索到所需的输出。我也尝试了Request.ServerVariables对象,但结果始终保持为NULL。

我正在使用asp.net MVC。这个功能是否需要改变:

public static string GetIP()
    {
        string functionReturnValue = null;
        //Gets IP of actual device versus the proxy (WAP Gateway)
        functionReturnValue = HttpContext.Current.Request.Headers["X-FORWARDED-FOR"]; //functionReturnValue = null
        if (string.IsNullOrEmpty(functionReturnValue))
        {
            functionReturnValue = HttpContext.Current.Request.Headers["X-Forwarded-For"];//functionReturnValue = null
            if (string.IsNullOrEmpty(functionReturnValue))
            {
                //If not using a proxy then get the device IP
                // GetIP = Context.Request.ServerVariables("REMOTE_ADDR")
                if (string.IsNullOrEmpty(functionReturnValue))
                {
                    //If not using a proxy then get the device IP
                    functionReturnValue = HttpContext.Current.Request.Headers["X-CLIENT-IP"];//functionReturnValue = null
                    if (string.IsNullOrEmpty(functionReturnValue))
                    {
                        //If not using a proxy then get the device IP
                        functionReturnValue = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];//functionReturnValue = "::1"
                    }
                }
            }
        }

        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\d{1,3}\\.){3}\\d{0,3}");
        if (functionReturnValue != null)
        {
            if (regex.IsMatch(functionReturnValue))
            {
                functionReturnValue = regex.Match(functionReturnValue).Value.ToString();
            }
            else
            {
                functionReturnValue = "";
            }
            regex = null;
        }

        if (functionReturnValue == null)
        {
            return "";
        }
        else
        {
            return functionReturnValue;
        }
    }

1 个答案:

答案 0 :(得分:1)

在X-Forwarded中 - 您将获得客户ipproxy1& proxy2。通过获取第一项,您将获得客户端/用户IP。

HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault()

希望它有所帮助!