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
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
How can I access HttpContext and开发者_StackOverflow中文版 from the controller initialization?
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.
精彩评论