Programs

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.

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

Explore our Popular Software Engineering Courses

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

 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  

Explore Our Software Development Free Courses

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

    }

 }

In-Demand Software Development Skills

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

}

Read our Popular Articles related to Software Development

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.

What are data structures in programming?

Data structures are the way we arrange data in a program. The two most important data structures are arrays and linked lists. Arrays are the most familiar data structure, and it is the easiest to understand. Arrays are basically numbered lists of related items. They are simple to understand and use, but they are not very efficient when working with large amounts of data. Linked lists are more complex, but they can be very efficient if used properly. They are good choices when you will have to add or remove items in the middle of a large list, or when you need to search for items in a large list.

What are the differences between linked list and arrays?

In arrays, an index is used to access an element. Elements in the array are organized in sequential order, which makes it easy to access and modify elements if an index is used. Array also has a fixed size. Elements are allocated at the time of its creation. In linked list, a pointer is used to access an element. Elements of a linked list are not necessarily stored in sequential order. A linked list has an unknown size because it can contain nodes at the time of its creation. A pointer is used to access an element, so memory allocation is easier.

What is a pointer in C?

A pointer is a data type in C which stores the address of any variable or function. It is generally used as a reference to another memory location. A pointer can hold a memory address of an array, structure, function or any other type. C uses pointers to pass values to and receive values from functions. Pointers are used to dynamically allocate memory space.

Want to share this article?

Become a Full Stack Developer

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks