Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Register action filter without modifying controller

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?

like image 750
Dan Ellis Avatar asked Jan 09 '12 09:01

Dan Ellis


People also ask

How action filter is implemented in MVC?

Mvc. FilterAttribute class. If you want to implement a particular type of filter, then you need to create a class that inherits from the base Filter class and implements one or more of the IAuthorizationFilter , IActionFilter , IResultFilter , or IExceptionFilter interfaces.

What step is required to apply a filter globally to every action in your application?

You need to add your filter globally, to add your filter to the global filter. You first need to add it on Global. asax file. You can use FilterConfig.

How do I register a global filter?

Open Global. asax file and locate the Application_Start method. Notice that each time the application starts it is registering the global filters by calling RegisterGlobalFilters method within FilterConfig class.

Can we override filters in MVC?

ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides. Using the Filter Overrides feature, we can exclude a specific action method or controller from the global filter or controller level filter. ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides.


2 Answers

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.

like image 140
sashaeve Avatar answered Oct 20 '22 19:10

sashaeve


If you want your filter to be registered for every action (or it is otherwise OK to do so), then MVC 3 allows you to apply Global action filters. Of course this requires that nopCommerce is built on MVC 3, which I believe the newest version is?

like image 42
rfmodulator Avatar answered Oct 20 '22 19:10

rfmodulator