加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 为什么我的ActionFilters都没有运行?

发布时间:2020-12-15 20:41:54 所属栏目:asp.Net 来源:网络整理
导读:我今天早些时候在 asked a question关于ASP.Net MVC中的ActionFilters.原来我的问题是我的ActionFilter甚至没有运行.除了我读过 this article的其他内容,我找不到他做的任何我不做的事情. 这是我的代码: // The ActionFilter itselfpublic class TestingIfI
我今天早些时候在 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”]保持空值.

为什么这不起作用?

解决方法

根据您对其他答案的评论

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

原版的

当然,您需要覆盖您的方法,否则您实际上并没有替换基类上的方法.我原以为编译器会抱怨你需要一个新的或覆盖它.如果您不包含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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读