Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null ControllerContext in my custom controller inheriting from BaseController

Tags:

asp.net-mvc

I built my own Controller class which inherits from BaseController. However the ControllerContext in constructor is "null". Where should I specify the ControllerContext?

like image 885
Brian J. Hakim Avatar asked Jul 13 '10 10:07

Brian J. Hakim


1 Answers

The ControllerContext property is not assigned to in any of the base constructors in your inheritance hierachy. A controller is created by a controller factory and passed back without the ControllerContext property being assigned to.

Using Reflector, we can look at where the assignment takes place:

protected virtual void Initialize(RequestContext requestContext)
{
    this.ControllerContext = new ControllerContext(requestContext, this);
}

The Initialize method is invoked from the virtual Execute method call:

protected virtual void Execute(RequestContext requestContext)
{
    if (requestContext == null)
    {
        throw new ArgumentNullException("requestContext");
    }
    this.VerifyExecuteCalledOnce();
    this.Initialize(requestContext);
    this.ExecuteCore();
}

This means the earliest point at which you can access the ControllerContext property is by overriding the Execute or Initialize method (but calling base.Execute or base.Initialize first):

protected override void Execute(RequestContext requestContext)
{
  base.Execute(requestContext);

  // .ControllerContext is available from this point forward.
}

protected override void Initialize(RequestContext requestContext)
{
  base.Initialize(requestContext);

  // .ControllerContext is available from this point forward.
}

The latter (Initialize) is the absolute earliest point at which you can use the ControllerContext property, unless you handled the assignment yourself, which is not recommended (as parts of the framework will be dependent on having that property assigned to at that time).

Hope that helps.

like image 190
Matthew Abbott Avatar answered Nov 15 '22 21:11

Matthew Abbott