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

zszep picture zszep · Mar 31, 2012 · Viewed 32.2k times · Source

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.

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 1, 2012

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();
}