I built my own Controller class which inherits from BaseController
. However the ControllerContext
in constructor is "null". Where should I specify the ControllerContext
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With