Use of MVC Custom Action Filter

Introduction

Action Filters provide us the ability to create an AOP (Aspect Oriented) approach with ASP.Net MVC. There are some builtin action filters provided by ASP.Net MVC like AuthorizeAttribute, HandleErrorAttribute and OutputCacheAttribute which enable us to run common code before the actual action method of the controller is called. AuthorizeAttribute and HandleErrorAttribute inherit from the FilterAttribute class and OutputCacheAttribute inherits from the abstract ActionFilterAttribute class.

Create Custom Action Filter

An Action Filter is implemented as the attribute class and it is inherited from the abstract class ActionFilterAttribute. It has four virtual methods OnActionExecuting, OnActionExecuted, OnResultExecuting, and OnResultExecuted that you may override. To implement the Action filter, you must implement at least one out of the four.

OnActionExecuting is called before the action method is called and OnActionExecuted is called after the action method is called. The OnResultExecuting method is called when the ActionResult is returned by your action is invoked. The OnResultExecuted method is called just after the result is executed.
When we create any action filter, at this time we can also provide their usage, which means we can also define the scope of those action filters used only for classes or methods etc.

Example:

In the following example, creating custom Action Filter called UserRightAttribute. It checks whether the user has the right, otherwise it redirects to the Error Page.

[AttributeUsage(AttributeTargets.All)]
public class UserRightAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //write your user right logic
        //if user has right to do nothig otherwise redirect to error page.
        string message = "You have no right to view this page.";
        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
        redirectTargetDictionary.Add("area", "");
        redirectTargetDictionary.Add("action", "Error");
        redirectTargetDictionary.Add("controller", "Home");
        redirectTargetDictionary.Add("customMessage", message);
        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);  
    }
}


The following code  shows how to use an Action Filter Attribute:

[UserRightAttribute]
public ActionResult About()
{
    return View();
}
public ActionResult Error(string customMessage)
{
    ViewModel.Message = customMessage;
    return View();
}


Conclusion

An action filter is useful when we write custom logic that runs directly before or directly after an action method runs. With help of an Action Filter we can perform tasks like logging, Authentication and other tasks.

Reference

http://msdn.microsoft.com/en-us/library/dd381609.aspx

Up Next
    Ebook Download
    View all
    Learn
    View all