ActionFilterAttribute in ASP.NET MVC Framework

I remember Scott Guthrie mentioning the ability to add filters to your controller actions, so immediately after downloading the ASP.NET MVC Framework Preview 2 I opened up Reflector and found a new ActionFilterAttribute in System.Web.Mvc.


 


ActionFilterAttribute 


 


Not bothering to see if there is any documentation on it, I decided to give it a whirl with the new ASP.NET MVC Website Template:


 


ASP.NET MVC Framework


 


I pretended the About Action on the Home Controller required an SSL connection and Administrative privileges to be run and added a couple of custom ActionFilterAttributes to it:


 


HomeController


 


 


Here is the sample code for the RequiresSSL ActionFilterAttribute:


 


RequiresSSL ActionFilterAttribute 


 


Here is the sample code for the AdminOnly ActionFilterAttribute:


 


AdminOnly ActionFilterAttribute


 


The key here is that when I set filterContext.Cancel = true it seems to cancel the action so I take advantage of it.


Note that in the AdminOnlyAttribute I cast the filter.Controller property, which comes in as IController, to Controller for kicks. Obviously this cast could return null, so you may want to go the HttpContext route again to get the roles for the user. I just felt like writing the code a bit differently.


There is a lot more you can do with ActionFilterAttributes, but this was interesting in itself.


Hope this helps.


David Hayden


 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

3 Responses to ActionFilterAttribute in ASP.NET MVC Framework

  1. Mark says:

    Hello your blog was userful for me. Thank you

  2. David Hayden says:

    I made the images smaller so you can see them in the browser fine. Hope that helps.

    Regards, Dave

  3. Mark says:

    Hi, everything is ok, just those pictures with code are too big in both ff and ie, maybe you could try http://pastie.caboo.se/ to show your code snippets or some similar page. Thank you

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>