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

Asp.net mvc 如何在asp.net mvc中获取静态类中的客户端ip地址,asp.net-mvc,model-view-controller,Asp.net Mvc,Model View Controller,我想在asp.net mvc 3中的静态类中获取客户端的ip地址 但我无法访问静态类中的请求对象 任何人都可以帮助如何在静态类中没有请求对象的情况下获取ip地址吗???您可以通过控制器的参数将HttpContext.Current传递给StaticClass,但这是一种不好的做法 最佳实践是在控制器的构造函数中获取实现类的接口 private readonly IService _service; public HomeController(IService service)

我想在
asp.net mvc 3
中的
静态类中获取客户端的ip地址

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


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

您可以通过控制器的参数将HttpContext.Current传递给StaticClass,但这是一种不好的做法

最佳实践是在控制器的构造函数中获取实现类的接口

 private readonly IService _service;

        public HomeController(IService service)
        {
            _service = service;
        } 
在服务舱

 private readonly HttpContextBase _httpContext;
  public Service (HttpContextBase httpContext)
        {
            _httpContext= httpContext;
        } 
然后使用IOC容器(Ninject、AutoFac等)解决依赖关系

AutoFac(global.asax)中的示例

builder.RegisterController(typeof(mvcapapplication.Assembly);
RegisterModule(新的AutofacWebTypesModule());
builder.RegisterType();

您可以在如下静态类中获取用户的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地址

它导致“请求在此上下文错误中不可用”
        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;