如何在asp.net mvc中的静态类中获取客户端IP地址

iCh*_*rag 11 model-view-controller asp.net-mvc

我想获得客户端的IP地址static classasp.net mvc 3.

但我无法访问静态类中的请求对象.

任何人都可以帮助如何在静态类中获取没有请求对象的IP地址?

Mar*_*ark 12

您可以在静态类中获取用户的IP地址,如下所示:

        string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ip))
        {
            ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        return ip;
Run Code Online (Sandbox Code Playgroud)

这种技术最好使用Request.UserHostAddress(),因为它有时只捕获用户代理的IP地址.