Custom Filter Attribute – ActionFilterAttribute

The ActionFilterAttribute class allows you to add custom behavior to a controller action method before or after it is executed. You can do this by overriding one or more of the methods provided by the class to implement your own custom logic that is executed either before or after the action method is called. This can be useful for a wide range of purposes, such as authentication and authorization, logging, or caching.

Example

For example, you could create a custom ActionFilterAttribute that authorize by Sitecore role on action method’s execution before or after it is called, like this:

using Sitecore.Security.Accounts;

public class SitecoreRoleAttribute : ActionFilterAttribute
{
    private readonly Role _role;
    public SitecoreRoleAttribute(Role role)
    {
       _role = role;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(Sitecore.Context.User.IsInRole(role))
           base.OnActionExecuting(filterContext);
        
        filterContext.Result = new RedirectResult("/");
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //same principle as above method
    }
}

In this example we create a custom action filter attribute called SitecoreRoleAttribute that inherits from ActionFilterAttribute. We override the OnActionExecuting and OnActionExecuted methods to execute code before or after executing the actionmethod is called. You could easily add some conditions in the methods to decide if the action should even be run.

To use this custom attribute, we can simply apply it to the action method we want to log like this:

[SitecoreRole(ACustomRole)]
public ActionResult MyActionMethod()
{
    ...
}

ACustomRole” above must be of the correct Type and you would’ve probably already have access to it in the constructor.

Now, whenever the MyActionMethod is called, the SitecoreRoleAttribute action filter will check the conditions before and after it is called.

Leave a comment