yeomandev
yeomandev

Reputation: 11796

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";
    }

}

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 from the controller initialization?

Upvotes: 6

Views: 4596

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 16

Related Questions