首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在controller.OnActionExecuting中设置结果后ActionFilter未触发

在controller.OnActionExecuting中设置结果后ActionFilter未触发
EN

Stack Overflow用户
提问于 2011-06-11 20:05:39
回答 2查看 2.5K关注 0票数 3

我有一个全局操作过滤器,它在OnActionExecuting事件期间设置所有ViewResults的MasterPage。

在我的许多控制器(每个控制器代表应用程序的一个功能)中,我需要检查是否启用了该功能,如果没有,则返回一个不同的视图。

代码如下:

代码语言:javascript
运行
复制
    protected override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (!settings.Enabled)
        {
            filterContext.Result = View("NotFound");
        }

        base.OnActionExecuting(filterContext);
    }

问题是,当像这样设置结果时,我的ActionFilter的OnActionExecuted方法不会触发,这意味着我没有应用正确的MasterPage。

我想知道为什么会发生这种情况。一种补救方法是将我的ActionFilter逻辑移到OnResultExecuting中(这确实会触发),但我仍然不明白为什么OnActionExecuted不能。

非常感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-11 21:45:31

如果将结果赋值给OnActionExecuting中的filterContext.Result,那么操作将不会执行=>,OnActionExecuted将永远不会运行。因此,在返回NotFound视图时,您可能需要在OnActionExecuting事件内应用正确的母版页:

代码语言:javascript
运行
复制
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()
        };
    }
}
票数 6
EN

Stack Overflow用户

发布于 2011-06-11 21:43:04

作为另一种选择,如何在_viewstart.cshtml中分配母版页(布局),而不用担心过滤器?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6315800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档