Web Developer, Software Engineer and Mixed Language Artist
RSS icon Email icon Home icon
  • Passing Parameters to an ActionFilter in ASP.NET MVC

    Posted on August 5th, 2010 Jamie 1 comment

    Creating action filters is quite a simple process. You can simply inherit from ActionFilterAttribute and bingo, you’ve got yourself a custom ActionFilter.

    There’s a lot of articles out in the wilderness of the web that explain how to go about creating custom ActionFilters and most of them are pretty good articles.

    The one thing I’ve not been able to find online is some instruction of how to create action filters that accept some kind of parameters. We already see this concept being used by such things as the OutputCacheAttribute action method where we can pass in a Duration, and various other parameters:

    ?View Code CSHARP
    [OutputCache(Duration = 5)]

    So how do we allow our own custom action filters to accept parameters in this same way?

    The answer seems really simple once you know however a search on Google doesn’t seem to return much in the way of any answers to this question (as with many of my posts, they’re usually things that I haven’t been able to find online already).

    The simple answer is that: Action filter parameters are properties of the action filter.

    Here’s a short example custom action filter that exposes a property which I then use when attaching the attribute to a class.

    ?View Code CSHARP
    public class CustomActionAttrbitue : ActionFilterAttribute
    {
         public int Id {get; set;}
         public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Do some work here.
        }
    }

    and in attaching this attribute to a class:

    ?View Code CSHARP
    [CustomAction(Id = 5)]
    public class MyController  : Controller
    {
     
    }

    Like I said above, once you know that the parameter is a property of the action filter, it seems obvious. Hope this helps someone else looking for this information.