如何在ASP.NET MVC的静态类中获取客户端IP地址

11

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

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

有没有人能帮忙提供在不使用请求对象的情况下获取 IP 地址的方法?

2个回答

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;

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


它会导致“请求在此上下文中不可用错误”。 - oneNiceFriend

1

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

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

 private readonly IService _service;

        public HomeController(IService service)
        {
            _service = service;
        } 

并且在Service类中

 private readonly HttpContextBase _httpContext;
  public Service (HttpContextBase httpContext)
        {
            _httpContext= httpContext;
        } 

然后使用IOC容器(Ninject,AutoFac等)来解决依赖关系

例如在AutoFac中(global.asax)

builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接