Skip to main content

ActionFilter in ASP.NET MVC

February 02, 2012 mgroves 0 Comments
Tags: asp.net mvc ActionFilter

AOP may sound like this big high-falutin' term that's way too complicated, but guess what: you may already be using AOP and you don't even know it.

Do you using ASP.NET MVC? Ever used an ActionFilter? Congratulations, you have used aspect-oriented programming. If you are using MVC and haven't used an ActionFilter yet, read on, because you may want to start!

Writing an ActionFilter is very similar to writing a PostSharp aspect: you create a new class that inherits from a base class (ActionFilterAttribute), and then you override one or more methods depending on what you want the ActionFilter to do.  You apply the aspect to a method or entire class with an attribute. Unlike PostSharp, this form of AOP does not involve a post-compile step. The filtering takes place at runtime, and is invoked by the MVC framework. This means that if you are writing a unit test against the controller action, that test will not trigger the ActionFilter.

I'm going to be blogging some more details about what you can do with each of these, but when you are creating a class that inherits from ActionFilterAttribute, there are 4 methods that you can override 1 or more of:

  • OnActionExecuting - runs before the affected action
  • OnActionExecuted - runs after the affected action
  • OnResultExecuting - runs before the result of the action runs
  • OnResultExecuted - runs after the result of the action runs

If you use the [Authorize] attribute in MVC, then you are using an ActionFilter that's been pre-written for you (technically AuthorizeAttribute inherits from FilterAttribute, but it's the same principle). Instead of checking the User.Identity inside every one of your Controller actions, you can just slap the [Authorize] attribute on it and it will keep that cross-cutting concern encapsulated away from the rest of your Controller logic.

Comments

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter