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?
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.
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With