从BaseController继承的自定义控制器中的null ControllerContext [英] Null ControllerContext in my custom controller inheriting from BaseController
问题描述
我建立了自己的Controller类,该类继承自BaseController
.但是,构造函数中的ControllerContext
为"null".我应该在哪里指定ControllerContext
?
I built my own Controller class which inherits from BaseController
. However the ControllerContext
in constructor is "null". Where should I specify the ControllerContext
?
推荐答案
在继承层次结构中的任何基本构造函数中均未分配ControllerContext
属性.控制器是由控制器工厂创建的,并在没有分配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.
使用Reflector,我们可以查看分配发生的位置:
Using Reflector, we can look at where the assignment takes place:
protected virtual void Initialize(RequestContext requestContext)
{
this.ControllerContext = new ControllerContext(requestContext, this);
}
Initialize
方法是从虚拟Execute方法调用中调用的:
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();
}
这意味着可以访问ControllerContext
属性的最早时间是通过覆盖Execute
或Initialize
方法(但首先调用base.Execute
或base.Initialize
):
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.
}
后一个(Initialize
)是可以使用ControllerContext属性的绝对最早点,除非您自己处理分配,否则不建议这样做(因为框架的某些部分取决于将那个属性分配给当时).
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).
希望有帮助.
这篇关于从BaseController继承的自定义控制器中的null ControllerContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!