Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable a global filter in ASP.Net MVC selectively

I have set up a global filter for all my controller actions in which I open and close NHibernate sessions. 95% of these action need some database access, but 5% don't. Is there any easy way to disable this global filter for those 5%. I could go the other way round and decorate only the actions that need the database, but that would be far more work.

like image 771
zszep Avatar asked Mar 31 '12 06:03

zszep


People also ask

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.

Can you specify different types of filters in ASP.NET MVC application?

The ASP.NET MVC framework supports four different types of filters: Authorization filters – Implements the IAuthorizationFilter attribute. Action filters – Implements the IActionFilter attribute. Result filters – Implements the IResultFilter attribute.

Is it possible to cancel filter execution?

You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value.

What is override MVC?

MVC Commands are used to break up the controller layer of a Liferay MVC application into smaller, more digestible code chunks. Sometimes you'll want to override an MVC command, whether it's in a Liferay application or another Liferay MVC application whose source code you don't own.


1 Answers

You could write a marker attribute:

public class SkipMyGlobalActionFilterAttribute : Attribute { } 

and then in your global action filter test for the presence of this marker on the action:

public class MyGlobalActionFilter : ActionFilterAttribute {     public override void OnActionExecuting(ActionExecutingContext filterContext)     {         if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(SkipMyGlobalActionFilterAttribute), false).Any())         {             return;         }          // here do whatever you were intending to do     } } 

and then if you want to exclude some action from the global filter simply decorate it with the marker attribute:

[SkipMyGlobalActionFilter] public ActionResult Index() {     return View(); } 
like image 179
Darin Dimitrov Avatar answered Sep 23 '22 12:09

Darin Dimitrov