【问题标题】:ActionFilterAttribute on method level inside MVC 5 is not triggeringMVC 5 内部方法级别的 ActionFilterAttribute 未触发
【发布时间】:2015-04-16 13:02:18
【问题描述】:

我已经阅读了一些关于属性的不同教程以及几个 StackOverflow 线程,但我无法辨别什么是正确的,什么不是。

我想用普通类中的属性装饰一个方法(无继承),并在调用该方法之前触发该方法。

HomeController.cs

public ActionResult Index()
{            
    var doStuff = new DoStuff();
    v = doStuff.Multiply(3, 3);
    return View();
}

DoStuff.cs

public class DoStuff
{
    [DoMoreStuff(typeof(DoStuff))]
    public int Multiply(int a, int b)
    {
        return a * b;
    }
}

DoMoreStuffAttribute.cs

using System;
using System.Web;
using System.Web.Mvc;

namespace Test.Models
{
    public class DoMoreStuffAttribute : ActionFilterAttribute
    {
        public DoMoreStuffAttribute(Type cls)
        {
            // cls i added to test something else in here.
            var f = 1; // Breakpoint added here
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var f = 1; // Breakpoint added here
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var f = 1; // Breakpoint added here
        }
    }
}

该属性永远不会被触发。如果我将它移到班级级别都没关系,它仍然永远不会被触发。

我在上面的代码中缺少什么?

【问题讨论】:

  • 您基本上需要在action method 上设置action filter。在执行操作之前,MVC 框架会检查操作过滤器属性,如果有,则执行它们。这不适用于在您的操作内部调用的方法。

标签: c# asp.net-mvc attributes action-filter actionfilterattribute


【解决方案1】:

如果没有任何自定义代码,我认为动作过滤器属性不适用于普通类(没有继承的类),它们只能用于控制器动作方法。

您可以通过自定义依赖注入使其工作,并通过拦截添加执行前/执行后。

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多