Null ControllerContext in my custom controller inheriting from BaseController

后端 未结 1 1105
后悔当初
后悔当初 2021-01-18 04:42

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

相关标签:
1条回答
  • 2021-01-18 05:30

    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.

    0 讨论(0)
提交回复
热议问题