Search code examples
c#asp.net-mvcattributesaction-filteractionfilterattribute

ActionFilterAttribute on method level inside MVC 5 is not triggering


I have read some different tutorials about Attributes and also several StackOverflow threads but am not able to discern what is correct and what isn't.

I wanted to decorate a method with an attribute inside a normal class (no inheritance) and have that trigger before the method is called.

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
        }
    }
}

The attribute never gets triggered. It doesn't matter if i move it to class level, it still never gets triggered.

What am i missing in the above code?


Solution

  • With out any custom code, I don't think Action Filter Attributes would work on normal classes(Class with No Inheritance), they would only work on controller action methods.

    You can make it work through custom dependency injection and add Before/After execution through interception.