我想在static class中的asp.net mvc 3中获取客户端的IP地址。

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

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

最佳答案

您可以像这样在静态类中获取用户的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;

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

09-30 13:02
查看更多