为什么我的ActionFilters都没有运行?

时间:2009-06-01 12:36:49

标签: asp.net-mvc action-filter

我今天早些时候asked a question关于ASP.Net MVC中的ActionFilters。原来我的问题是我的ActionFilter甚至没有运行。除了我读this article之外的其他内容,我找不到他做的任何我不做的事。

这是我的代码:

// The ActionFilter itself
public class TestingIfItWorksAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.TempData["filter"] = "it worked!";
        base.OnActionExecuting(filterContext);
    }
}

// The Controller Action with the filter applied
[TestingIfItWorks]
public ActionResult Test()
{
    var didit = TempData["filter"];
    return View();
}

调试时,过滤器方法中的断点永远不会被击中,并且TempData["filter"]在呈现视图时保持null值。

为什么这不起作用?

3 个答案:

答案 0 :(得分:7)

如果它对使用MVC 4/5的任何人有帮助:

如果您获得ActionFilterAttributeIActionFilter错误的命名空间,

ActionFilters不会运行:https://stackoverflow.com/a/13710468/188926

对Web API使用System.Web.Http.Filters,对标准MVC操作使用System.Web.Mvc

在问题中,如果你弄错了,过滤器属性将被忽略(没有错误),这使得诊断变得困难。

答案 1 :(得分:4)

根据您对其他答案的评论

通过单元测试进行测试时,不会调用过滤器。如果要调用过滤器,则需要模拟ControllerActionInvoker。最好是单独测试过滤器本身,然后使用反射来确保过滤器应用于具有正确属性的操作。我更喜欢这种机制而不是组合测试过滤器和动作。

<强>原始

当然,您的方法需要override,否则您实际上并没有替换基类上的方法。我本来希望编译器抱怨你需要newoverride。如果您不包含override关键字,则其行为就像您使用new一样。由于框架将其作为ActionFilterAttribute调用,这意味着您的方法永远不会被调用。

引自MSDN

  

如果派生类中的方法是   没有新的或覆盖之前   关键字,编译器会发出一个   警告和方法将表现为   如果新关键字存在。

答案 2 :(得分:0)

除了tvanofosson所说的,你的动作方法实际上并没有向视图呈现任何东西。您的观点是否有<%=TempData["Filter"].ToString()%>声明或类似内容?