Quantcast
Channel: Sampath Lokuge Tech Blog
Viewing all articles
Browse latest Browse all 107

How to Create a Custom Action Filter for MVC 3 ?

$
0
0
What is an Action Filter ?
  • It's an Attribute
  • Could be applied on a particular Action
  • Could be applied on a Controller
  • It modifies the way Action Executes
  • An Action Filter is a class that inherits from the FilterAttributebase class
  • Filters are used to inject an extra logic into the MVC request processing
  • Filters to define logic which is used to apply add-on functionality to the application
  • e.g. defining Authorization, Caching, Logging, Exception etc.

What are the Types of Action Filters ?



What is 1-2-3-4 ?
  • If an Action Method has more than OneAction Filter applied,
  • Then the order in which they are executed
  • i.e.Action Filters are Executed in the order 1-2-3-4 
  • Firstly Executes Authorization Filters
  • Lastly ExecutesException Filters


What is an Authorization Filter ?
  • These filters are always run first before any other filters
  • They implement IAuthorizationFilter interface
  • Provides AuthorizeAttribute as the default class implementation

How to Do That ?

MyAuthorizationFilterAttribute.cs

using System.Web.Mvc;

namespace CustomActionFilter.CustomActionFilters
 {
 publicclassMyAuthorizationFilterAttribute:FilterAttribute,IAuthorizationFilter
  {
      publicvoid OnAuthorization(AuthorizationContextfilterContext)
      {
          if(filterContext.HttpContext.Request.IsAuthenticated)
          {
              //The action filter logic
          }
      }
  }
}


HomeController.cs

using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;

namespace CustomActionFilter.Controllers
{
    publicclassHomeController: Controller
    {
        [MyAuthorizationFilter]
        publicActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            returnView();
        }
    }
}


What is an Action Filter ?
  • It Implements IActionFilter interface
  • It Executesbefore and after action result is executed
  • Provides ActionFilterAttribute as the default class implementation

How to Do That ?

MyActionFilterAttribute.cs

using System.Web.Mvc;

namespace CustomActionFilter.CustomActionFilters
{
    publicclassMyActionFilterAttribute: FilterAttribute, IActionFilter
    {
        publicvoid OnActionExecuting(ActionExecutingContextfilterContext)
        {
            //The action filter logic - before
        }

        publicvoid OnActionExecuted(ActionExecutedContextfilterContext)
        {
            //The action filter logic - after
        }
    }
}

HomeController.cs

using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;

namespace CustomActionFilter.Controllers
{
    publicclassHomeController: Controller
    {
        [MyActionFilter]
        publicActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            returnView();
        }
    }
}

What is a Result Filter ?
  • It Implements IResultFilter interface
  • It Executes before and after action result is executed

How to Do That ?

MyResultFilterAttribute.cs

using System.Web.Mvc;

namespace CustomActionFilter.CustomActionFilters
{
    publicclassMyResultFilterAttribute: FilterAttribute, IResultFilter
    {
        publicvoid OnResultExecuting(ResultExecutingContextfilterContext)
        {
            //The action filter logic - before
        }

        publicvoid OnResultExecuted(ResultExecutedContextfilterContext)
        {
            //The action filter logic - after
        }
    }
}

HomeController.cs

using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;

namespace CustomActionFilter.Controllers
{
    publicclassHomeController: Controller
    {
        [MyResultFilter]
        publicActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            returnView();
        }
    }
}


What is an Exception Filter ?
  • It Implements IExceptionFilter interface
  • It Executes only if exception is thrown by action method or an action result
  • Provides HandleErrorAttribute as the default class implementation

How to Do That ?

MyExceptionFilterAttribute.cs

using System.Web.Mvc;

namespace CustomActionFilter.CustomActionFilters
{
    publicclassMyExceptionFilterAttribute: FilterAttribute, IExceptionFilter
    {
        publicvoid OnException(ExceptionContextfilterContext)
        {
            if(filterContext.Exception != null)
            {
                //The action filter logic
            }
        }
    }
}

HomeController.cs

using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;

namespace CustomActionFilter.Controllers
{
    publicclassHomeController: Controller
    {
        [MyExceptionFilter]
        publicActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            returnView();
        }
    }
}


Note :

  • I have used VS 2010 with Asp.Net MVC 3 and C# for develop above code samples.


CustomActionFilter's Project Tree is as below :



Finally, the HomeController with All the Custom Action Filters are as below :

using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;

namespace CustomActionFilter.Controllers
{
    publicclassHomeController: Controller
    {
        [MyAuthorizationFilter]
        [MyActionFilter]
        [MyResultFilter]
        [MyExceptionFilter]
        publicActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            returnView();
        }
    }
}

That's It.You're Done. 

Do you need to Download this Sample Project ?



Conclusion
  • Action Filters allow you to do some extra pre or post processing to be carried out,in addition to the code written in the action methods
  • Depending on your need you can implementIAuthorizationFilter, IActionFilter, IResultFilter or IExceptionFilter interfaces to make your filter an Authorization filter, Action filter, Result filter or Exception filter respectively
  • These interfaces decide the order in which the action filters are executed
  • Which makes your application more flexible and maintainable


I hope this helps to You.Comments and feedback greatly appreciated.


Happy Coding.


You Might Also Like

How to Improve ASP.Net MVC 3 View Performance ?
How to Use ViewModel with ASP.NET MVC ?
How to use Asp.Net MVC TempData Properly ?


Viewing all articles
Browse latest Browse all 107

Trending Articles