Skipping ActionFilters in ASP.NET MVC

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

 
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
	bool skipImportantTaskFilter = filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipImportantTaskAttribute), true) ||
		filterContext.ActionDescriptor.IsDefined(typeof(SkipImportantTaskAttribute), true);

	if (!skipImportantTaskFilter)
	{
		PerformModelAlteration(filterContext);
	}

	base.OnActionExecuted(filterContext);
}

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

Full source code here.

Leave a Reply

Your email address will not be published. Required fields are marked *