The ControllerContext property is not assigned any of the base constructors in the inheritance hierarchy. The controller is created by the factory controller and passed back without assigning the ControllerContext property.
Using the Reflector, we can see where the assignment takes place:
protected virtual void Initialize(RequestContext requestContext) { this.ControllerContext = new ControllerContext(requestContext, this); }
The Initialize method is called from a virtual call to the Execute method:
protected virtual void Execute(RequestContext requestContext) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } this.VerifyExecuteCalledOnce(); this.Initialize(requestContext); this.ExecuteCore(); }
This means that the earliest point at which you can access the ControllerContext property is to override the Execute or Initialize method (but first call base.Execute or base.Initialize ):
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 have processed the assignment yourself, which is not recommended (since parts of the structure will depend on that at the time).
Hope this helps.
Matthew Abbott Jul 13 '10 at 10:52 2010-07-13 10:52
source share