Skipping ActionFilters in ASP.NET MVC

Full source code here.

In the previous post I showed how you can use an action filter to execute code both before and after an action method and how to apply the filter globally.

I found myself in a scenario where I wanted to run the action filter almost globally. I needed to exclude all actions methods in one controller and one action method in another controller.

This is easily done with the use of an Attribute, see here for more.

Create a SkipImportantTaskAttribute like so -

  public class SkipImportantTaskAttribute : Attribute {}

I then decorate the relevant action methods or controllers with this attribute. To skip an entire controller do this -

    [SkipImportantTask]
    public class CustomersController : Controller

To skip just a single action method do this -

	[SkipImportantTask]
	public ActionResult Index()

Change the OnActionExecuted (or OnActionExecuting) method of the action filter to the following

 1public override void OnActionExecuted(ActionExecutedContext filterContext)
 2{
 3	bool skipImportantTaskFilter = filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipImportantTaskAttribute), true) ||
 4		filterContext.ActionDescriptor.IsDefined(typeof(SkipImportantTaskAttribute), true);
 5
 6	if (!skipImportantTaskFilter)
 7	{
 8		PerformModelAlteration(filterContext);
 9	}
10
11	base.OnActionExecuted(filterContext);
12}

Now if SkipImportantTaskAttribute is present on the controller or action method the action filter code will not be executed.

Full source code here.

comments powered by Disqus

Related