我想在asp.net mvc 3中获取客户端在static class中的ip地址。
但是我不能访问静态类中的请求对象。
谁能帮我在静态类中不带request对象的情况下获取ip地址??
发布于 2012-01-27 19:18:14
您可以在静态类中获取用户的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地址。
发布于 2012-01-27 19:11:08
您可以通过控制器的参数向StaticClass传递HttpContext.Current,但这是一个不好的做法。
最佳实践是在控制器的构造函数中获取实现类的接口。
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();https://stackoverflow.com/questions/9032202
复制相似问题