我有一个全局操作过滤器,用于在OnActionExecuting事件期间设置所有ViewResults的MasterPage。
在我的许多控制器中(每个控制器代表应用程序的一个功能)我需要检查该功能是否已启用,如果没有,则返回不同的视图。
以下是代码:
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (!settings.Enabled)
{
filterContext.Result = View("NotFound");
}
base.OnActionExecuting(filterContext);
}
问题是,当设置这样的结果时,我的ActionFilter的OnActionExecuted方法不会触发,这意味着我没有应用正确的MasterPage。
我想了解为什么会这样。一个补救措施是将我的ActionFilter逻辑移动到OnResultExecuting(这确实会触发),但我仍然对OnActionExecuted为什么不这样做感到困惑。
非常感谢
本
答案 0 :(得分:6)
如果您将结果分配给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()
};
}
}
答案 1 :(得分:0)
作为替代方法,如何在_viewstart.cshtml中分配母版页(布局)而不用担心过滤器?