ASP.NET MVC: Register action filter without modifying controller

Dan Ellis picture Dan Ellis · Jan 9, 2012 · Viewed 21.9k times · Source

I'm working with nopCommerce and I need to add in my only Action Filter, however, I don't want to modify the core controllers to avoid my code being overwritten when a new update is released.

I've setup my Action Filter:

public class ProductActionFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            ...
        }
        base.OnActionExecuted(filterContext);
    }

}

If I were to modify the controller, I could just add [ProductActionFilter] to the action I want it assigned to.

Is there a way I can register my custom Action Filter to a specific action without modifying the controller?

Answer

sashaeve picture sashaeve · Jan 9, 2012

I think global filters is what you need.

Once you created the filter register it in the global.asax:

protected void Application_Start() {

    AreaRegistration.RegisterAllAreas();

    // Register global filter
    GlobalFilters.Filters.Add(new MyActionFilterAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes); 
}

Add custom validation logic to filter if you want to apply it not to all actions.