gpt4 book ai didi

asp.net-mvc - 为什么我的所有ActionFilter都不运行?

转载 作者:行者123 更新时间:2023-12-04 06:13:21 25 4
gpt4 key购买 nike

我今天早些时候在ASP.Net MVC中使用ActionFilters进行asked a question。原来,我的问题确实是我的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();
}

当我调试时,filter方法中的断点永远不会命中,并且渲染 View 时 TempData["filter"]保留 null值。

为什么这不起作用?

最佳答案

根据您对另一个答案的评论

通过单元测试进行测试时,不调用过滤器。如果要调用过滤器,则需要模仿ControllerActionInvoker。最好单独测试过滤器,然后使用反射来确保将过滤器以正确的属性应用于您的操作。与组合测试过滤器和操作相比,我更喜欢这种机制。

原始

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

引用MSDN:

If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.

关于asp.net-mvc - 为什么我的所有ActionFilter都不运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/934647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com