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.
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:

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:

Here is the sample code for the RequiresSSL ActionFilterAttribute:
Here is the sample code for the 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
Posted
Wed, Mar 5 2008 6:16 PM
by
David Hayden