ASP.NET MVC: Ignore custom attribute in a base controller class

MegaMatt picture MegaMatt · Dec 8, 2010 · Viewed 7k times · Source

I have a number of Controllers in my project that all inherit from a controller I've named BaseController. I wrote a custom attribute that I applied to the entire BaseController class, so that each time an action runs in any of my controllers, that attribute will run first.

The problem is that I have a couple of controller actions that I'd like to ignore that attribute, but I don't know how to do it.

Can anyone help? I'm using MVC 1.

Thanks.

Answer

Johnny Oshika picture Johnny Oshika · Dec 8, 2010

In your custom attribute, you can add this ShouldRun() check like this:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (ShouldRun(filterContext))
        {
            // proceed with your code
        }
    }

    private bool ShouldRun(ActionExecutingContext filterContext)
    {
        var ignoreAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(IgnoreMyCustomAttribute), false);
        if (ignoreAttributes.Length > 0)
            return false;

        return true;
    }

ShouldRun() simply checks whether there's a "IgnoreMyCustomAttribute" on your action. If it's there, then your custom attribute won't do anything.

You'll now want to create a simple IgnoreMyCustomAttribute, which doesn't do anything:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class IgnoreMyCustomAttribute: ActionFilterAttribute
{
}

Whenever you decorate your controller action with [IgnoreMyCustom], then MyCustomAttribute won't do anything. e.g.:

[IgnoreMyCustom]
public ViewResult MyAction() {
}