Action Filters in MVC [Types of Filters with Examples]
Updated on Dec 30, 2024 | 6 min read | 11.4k views
Share:
For working professionals
For fresh graduates
More
Updated on Dec 30, 2024 | 6 min read | 11.4k views
Share:
Table of Contents
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.
Check out our free courses to get an edge over the competition.
Also Read: MVC Project
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.
Check out upGrad’s Advanced Certification in Blockchain
Filter pipeline in request and response life cycle flow:
The filter provides two categories of implementing the logic in code, it performs different interface definitions-
Check out upGrad’s Advanced Certification in Cloud Computing
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 are described with a single method, which has the methods of
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);
}
}
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
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.
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();
}
We can describe the Action filters before performing the Action Method and after the action method.
It holds two types of methods.
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);
}
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.
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);
}
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
Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
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 Executive PG Program 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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources