我想在的static class
中获取客户端的ip地址。如何在asp.net的静态类中获取客户端ip地址mvc
但我无法访问静态类中的请求对象。
任何一个可以帮助如何获得没有请求对象的IP地址在静态类?
我想在的static class
中获取客户端的ip地址。如何在asp.net的静态类中获取客户端ip地址mvc
但我无法访问静态类中的请求对象。
任何一个可以帮助如何获得没有请求对象的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地址。
您可以通过控制器的参数将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 Containner(Ninject,AutoFac等),用以解决相关性
为例在AutoFac(Global.asax中)
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();
它导致“请求在此上下文中不可用错误” – oneNiceFriend 2017-03-14 10:50:32