Action Filters in MVC [Types of Filters with Examples]

ASP.NET MVC – Action Filters

In MVC (Model-View-Controller) filters, we use the additional logic as per the different functionalities or logic from the MVC Framework request processing.

MVC filters implement a process for different levels: for example, authorisation, logging, and caching.

We can consider an Action filter as an attribute we can implement to a controller action method to do the modification as per the business logic.

We can consider MVC filters from the system. The attribute is defined as the class, method, properties, and fields.

Also Read: MVC Project 

The ASP.NET MVC Framework Incorporates Various Action Filters

Authorise: This action filter has the capability of restricting access to a specific user role.

OutputCache: It is the action filter, and caches the outcome of a controller action method in the defined time.

HandleError: When this controller action executes, it handles the errors in a particular scenario if the code fails. It allows you to create your custom action filter.

 For example, we can create a custom action filter to execute a custom authentication system.

 Source

Filter pipeline in request and response life cycle flow:

Source 

The filter provides two categories of implementing the logic in code, it performs different interface definitions-

  1. Synchronous  
  2. Asynchronous  

The Synchronous Filters 

In the Synchronisation filter, we can run the code before and after the pipeline when it processes; we can consider it as OnStageExecuting and OnStageExecuted action methods.

Asynchronous Filters

 Asynchronous filters are described with a single method, which has the methods of 

  • OnActionExecuting
  • OnActionExecuted
  • OnActionExecutionAsync

The code snippets below are the type of declaration 

public class TimestampFilter : IActionFilter, IAsyncActionFilter 

{    

    public void OnActionExecuting(ActionExecutingContext context)    

    {         

        context.ActionDescriptor.RouteValues[“timestamp”] = DateTime.Now.ToString();    

    }

    public void OnActionExecuted(ActionExecutedContext context)    

    {         

        var ts = DateTime.Parse(context.ActionDescriptor. RouteValues[“timestamp”]).AddHours(1).ToString();        

        context.HttpContext.Response.Headers[“X-EXPIRY-TIMESTAMP”] = ts;    

    }

     public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)    

    {        

        this.OnActionExecuting(context);        

        var resultContext = await next();

        this.OnActionExecuted(resultContext);    

    }

 }

Types of Action Filters in MVC

The ASP.NET MVC framework maintains various filters:

Authorisation filters: Executes the IAuthorisationFilter attribute.

Action filters: Performs the IActionFilter attribute.

Result filters: Execute the IResultFilter attribute.

Exception filters: Executes the IExceptionFilter attribute.

Authorisation Filters

We can use it for the user’s accessibility, and we can declare it before the implementation of the action method in the controller.

Authorisation Filter enables two built-in attributes, for example: Authorise and AllowAnonymous 

We can use these in custom logic in the code as per our business requirement. 

The code snippet below is the example of Authorisation filters

[Authorise]

public ActionResult SecureMethod()

{

    return View();

}

[AllowAnonymous]

 public ActionResult NonSecureMethod()

    {

        return View();

    }

 public ActionResult SecureMethod()

    {

        return View();

    }

Action Filters

We can describe the Action filters before performing the Action Method and after the action method. 

It holds two types of methods.

  1. OnActionExecuted
  2. OnActionExecuting

The code snippet below is the example of Action Filters

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace TutorialActionFilter.Filters

{

public class Myactionfilter : FilterAttribute,IActionFilter

{

public void OnActionExecuted(ActionExecutedContext filterContext)

{

if (filterContext.HttpContext.Session[“UserID”] != null)

{

filterContext.Result = newRedirectResult(“/Home/Index”);

}

else

{

filterContext.Result = newRedirectResult(“/Login /Login”);

}

}

public void OnActionExecuting(ActionExecutingContext filterContext)

{

if (filterContext.HttpContext.Session[“UserID”] != null)

{

filterContext.Result = newRedirectResult(“/Home/ Index”);

}

else

{

filterContext.Result = newRedirectResult(“/Login /Login”);

}

}

}

}

[TutorialActionFilter]

[AcceptVerbs(HttpVerbs.Get)]

public ActionResult GetPerson()

{

Person p = new Person ();

return View(“Person”,p);

}

Result Filters

We can describe the Action filters before performing the Action Method and after the Action Method has been performed. 

It holds two types of methods.

  1. OnResultExecuted
  2. OnResultExecuting

The code snippet below is the example of Result Filters

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace ResultFilter.Filters

{

public class MyResultfilter : FilterAttribute,IResultFilter

{

public void OnResultExecuted(ResultExecutedContext filterContext)

{

if (filterContext.HttpContext.Session[“UserID”] != null)

{

filterContext.Result = newRedirectResult(“/Home/Contact”);

}

else

{

filterContext.Result = newRedirectResult(“/Login/Login”);

}

}

 

public void OnResultExecuting(ResultExecutingContext filterContext)

{

if (filterContext.HttpContext.Session[“UserID”] != null)

{

filterContext.Result = newRedirectResult(“/Home/Contact”);

}

else

{

filterContext.Result = newRedirectResult(“/Login/Login”);

}

}

}

}

[MyResultfilter]

[AcceptVerbs(HttpVerbs.Get)]

public ActionResult GetPerson()

{

Person p = newPerson ();

return View(“Person”,p);

}

Exception Filters 

We can use these when a controller or action method throws the exception.

This exception filter is important to catch the exception.

Below is the code snippet to use exception filters 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace ExceptionFilter.Filters

{

public class MyExceptionFilter : FilterAttribute, IExceptionFilter

{

public void OnException(ExceptionContext filterContext)

{

filterContext.Controller.ViewBag.onExceptionError = “ExceptionFilter filter called”;

filterContext.HttpContext.Response.Write(“ExceptionFilter filter called”);

}

}

}

[MyExceptionFilter]

public class HomeController : Controller

{

[AcceptVerbs(HttpVerbs.Get)]

public ActionResult GetPerson()

{

Person p = newPerson ();

return View(“Person”,p);

}

}

Also Read: Java MVC Project

Conclusion

We hope this article helped you with the understanding of the Action filters in MVC.

If you’re interested to learn more about full-stack development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Become a Full Stack Developer

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
APPLY NOW

Leave a comment

Your email address will not be published.

×