【问题标题】:how to get client ip address in static class in asp.net mvc如何在asp.net mvc的静态类中获取客户端IP地址
【发布时间】:2012-01-27 10:50:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: asp.net-mvc model-view-controller


    【解决方案1】:

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

    【讨论】:

    • 导致“Request is not available in this context 错误”
    【解决方案2】:

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

    一个最佳实践是在Controller的构造函数中获取实现类的接口。

     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.RegisterControllers(typeof(MvcApplication).Assembly);
    builder.RegisterModule(new AutofacWebTypesModule());
    builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();
    

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 2011-02-04
      • 2016-02-17
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2020-05-16
      相关资源
      最近更新 更多