我有一个全局操作过滤器,它在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不能。
非常感谢
本
发布于 2011-06-11 21:45:31
如果将结果赋值给OnActionExecuting中的filterContext.Result,那么操作将不会执行=>,OnActionExecuted将永远不会运行。因此,在返回NotFound视图时,您可能需要在OnActionExecuting事件内应用正确的母版页:
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()
};
}
}发布于 2011-06-11 21:43:04
作为另一种选择,如何在_viewstart.cshtml中分配母版页(布局),而不用担心过滤器?
https://stackoverflow.com/questions/6315800
复制相似问题