为什么我不能从控制器初始化访问的HttpContext? [英] Why can't I access the HttpContext from the Controller initializer?
问题描述
我已经建立了这样一个控制器:
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";
}
}
我的所有其他控制器,从这个GenesisController继承。每当我运行应用程序,我得到这个错误说
All of my other controllers inherit from this GenesisController. Whenever I run the application, i get this error saying
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
我
如何访问的HttpContext从控制器初始化?
How can I access HttpContext and from the controller initialization?
推荐答案
由于HttpContext的是未在控制器构造提供。你可以重写初始化方法,它可以被访问,就像这样:
Because the HttpContext is not available in the controller constructor. You could override the Initialize method where it will be accessible, like this:
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.
这篇关于为什么我不能从控制器初始化访问的HttpContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!