Ben*_*ter 3 c# action-filter asp.net-mvc-3
我有一个全局操作过滤器,它在OnActionExecuting事件期间设置所有ViewResults的MasterPage.
在我的许多控制器中(每个控制器代表应用程序的一个功能)我需要检查功能是否已启用,如果没有,则返回不同的视图.
这是代码:
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (!settings.Enabled)
{
filterContext.Result = View("NotFound");
}
base.OnActionExecuting(filterContext);
}
Run Code Online (Sandbox Code Playgroud)
问题是,当设置这样的结果时,我的ActionFilter的OnActionExecuted方法不会触发,这意味着我没有应用正确的MasterPage.
我想明白为什么会这样.一个补救措施是将我的ActionFilter逻辑移动到OnResultExecuting(这确实会触发),但我仍然对OnActionExecuted为什么不这样做感到困惑.
非常感谢
本
如果您将结果分配给filterContext.Result内部,OnActionExecuting则操作将不会执行=> OnActionExecuted将永远不会运行.因此,您可能需要OnActionExecuting在返回NotFound视图时在事件内应用正确的母版页:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!settings.Enabled)
{
// Because we are assigning a Result here the action will be
// short-circuited and will never execute neither the OnActionExecuted
// method of the filer. The NotFound view will be directly rendered
filterContext.Result = new ViewResult
{
ViewName = "NotFound",
MasterName = GetMasterName()
};
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2083 次 |
| 最近记录: |