I have a controller set up like this:
我有一个这样的控制器设置:
public class GenesisController : Controller
{
private string master;
public string Master { get { return master; } }
public GenesisController()
{
bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
if (mobile)
master="mobile";
else
master="site";
}
}
All of my other controllers inherit from this GenesisController. Whenever I run the application, i get this error saying
我的所有其他控制器都继承自这个GenesisController。每当我运行应用程序时,我都会收到此错误消息
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
How can I access HttpContext and from the controller initialization?
如何从控制器初始化访问HttpContext?
1 个解决方案
#1
15
Because the HttpContext is not available in the controller constructor. You could override the Initialize method where it will be accessible, like this:
因为HttpContext在控制器构造函数中不可用。您可以覆盖可以访问它的Initialize方法,如下所示:
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
if (mobile)
master="mobile";
else
master="site";
}
Also I bet that what you are trying to do with this master variable and booleans might be solved in a far more elegant way than having your controllers worry about stuff like this.
另外我敢打赌,你试图用这个主变量和布尔值做的事情可能会比让你的控制器担心这样的事情更加优雅。
#1
15
Because the HttpContext is not available in the controller constructor. You could override the Initialize method where it will be accessible, like this:
因为HttpContext在控制器构造函数中不可用。您可以覆盖可以访问它的Initialize方法,如下所示:
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
if (mobile)
master="mobile";
else
master="site";
}
Also I bet that what you are trying to do with this master variable and booleans might be solved in a far more elegant way than having your controllers worry about stuff like this.
另外我敢打赌,你试图用这个主变量和布尔值做的事情可能会比让你的控制器担心这样的事情更加优雅。