View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Action Filters in MVC [Types of Filters with Examples]

By Rohan Vats

Updated on Dec 30, 2024 | 6 min read | 11.4k views

Share:

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.

Check out our free courses to get an edge over the competition.

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.

Check out upGrad’s Advanced Certification in Blockchain

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

 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

Check out upGrad’s Advanced Certification in Cloud Computing

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);    

    }

 }

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

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

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.

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 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.

Frequently Asked Questions (FAQs)

1. What are data structures in programming?

2. What are the differences between linked list and arrays?

3. What is a pointer in C?

Rohan Vats

408 articles published

Get Free Consultation

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program