A Complete Guide - ASP.NET MVC Action Filters and their Types

Last Updated: 03 Jul, 2025   
  YOU NEED ANY HELP? THEN SELECT ANY TEXT.

ASP.NET MVC Action Filters and Their Types

Understanding Action Filters

In ASP.NET MVC, the action execution pipeline is a sequence of events that occur from the point a request is received by the MVC framework until the action method is executed and the response is sent back to the client. Action Filters play a critical role in this pipeline by allowing custom code to execute before the action method is called (OnActionExecuting) and after it has executed (OnActionExecuted). Here's a simplified view of the pipeline stages:

  1. Authorization Filter – Determines whether the user is authorized to execute the action.
  2. Action Filter – Pre-action and post-action execution.
  3. Action Method – Executes the specified action.
  4. Result Filter – Handles the output processing before the action result is executed.
  5. Exception Filter – Catches and handles exceptions that occur during the pipeline.

Lifecycle of Action Filters

  • OnActionExecuting: Called immediately before the action method executes. It provides an opportunity to inspect or modify the input parameters, cancel the action method execution, or set additional action-specific data.
  • OnActionExecuted: Called immediately after the action method executes, regardless of whether it completed successfully or an exception was thrown. It enables you to manipulate the action result, handle exceptions, or perform cleanup tasks.

Implementing Action Filters

You can create Action Filters by inheriting from ActionFilterAttribute and overriding its methods. Below is a simple example that demonstrates how to log action execution details:

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Log before the action executes
        Debug.WriteLine($"Executing action: {filterContext.ActionDescriptor.ActionName}");
        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Log after the action executes
        Debug.WriteLine($"Executed action: {filterContext.ActionDescriptor.ActionName}");
        base.OnActionExecuted(filterContext);
    }
}

To apply the LogActionFilter to an action method or a controller, simply decorate it:

[LogActionFilter]
public ActionResult Index()
{
    return View();
}

Types of Action Filters

ASP.NET MVC provides several built-in Action Filters, and you can also create custom implementations. Here are the key types:

  1. ActionFilterAttribute: The base class for action filters. It provides the OnActionExecuting and OnActionExecuted methods for you to override.

  2. HandleErrorAttribute: Inherits from ActionFilterAttribute. It simplifies exception handling by providing a convenient way to specify custom error pages for different types of exceptions.

    [HandleError(ExceptionType = typeof(ArgumentException), View = "ErrorArgument")]
    public ActionResult Index()
    {
        // Action logic
    }
    
  3. OverrideActionFiltersAttribute: Allows you to override the action filters applied at the controller level for a specific action method.

    [OverrideActionFilters]
    [AuthorizationFilter]
    public ActionResult Details(int id)
    {
        // Action logic
    }
    
  4. ValidateAntiForgeryTokenAttribute: Another action filter, used to prevent cross-site request forgery (CSRF) attacks. It checks the request for a valid anti-forgery token.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET MVC Action Filters and their Types

Prerequisites

  • Basic knowledge of ASP.NET MVC
  • C# Programming
  • Visual Studio (or any similar IDE)

Step 1: Create a New ASP.NET MVC Web Application

  1. Open Visual Studio
  2. Create a New Project:
    • Go to File > New > Project
    • Select ASP.NET Web Application (.NET Framework)
    • Name your project ActionFiltersExample and click Create
  3. Select Template:
    • Choose MVC from the available templates and click Create

Step 2: Create Action Filters

Action Filters can be categorized into two main types:

  1. OnActionExecuting: This method executes before the action method is called.
  2. OnActionExecuted: This method executes after the action method is called.

There are also two other methods: 3. OnResultExecuting: This method executes before the action result is executed. 4. OnResultExecuted: This method executes after the action result is executed.

We will create an example for each of these.

Step 3: Implement Action Filters

Step 3.1: Create a Custom Action Filter

  1. Create a Filter Folder:

    • Right-click on the project in the Solution Explorer.
    • Select Add > New Folder and name it Filters.
  2. Create an Action Filter Class:

    • Right-click on the Filters folder in the Solution Explorer.
    • Select Add > New Item.
    • Select Class and name it MyCustomActionFilter.cs.
    • Implement the ActionFilterAttribute class.
    using System.Diagnostics;
    using System.Web.Mvc;
    
    namespace ActionFiltersExample.Filters
    {
        public class MyCustomActionFilter : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                Debug.WriteLine("OnActionExecuting - Before Action Method Executes");
            }
    
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                Debug.WriteLine("OnActionExecuted - After Action Method Executes");
            }
    
            public override void OnResultExecuting(ResultExecutingContext filterContext)
            {
                Debug.WriteLine("OnResultExecuting - Before Action Result Executes");
            }
    
            public override void OnResultExecuted(ResultExecutedContext filterContext)
            {
                Debug.WriteLine("OnResultExecuted - After Action Result Executes");
            }
        }
    }
    

Step 3.2: Use the Custom Action Filter

  1. Modify the HomeController:

    • Open the HomeController class located in the Controllers folder.
    • Apply the MyCustomActionFilter attribute to the Index action method.
    using System.Web.Mvc;
    using ActionFiltersExample.Filters;
    
    namespace ActionFiltersExample.Controllers
    {
        public class HomeController : Controller
        {
            [MyCustomActionFilter]
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
        }
    }
    
  2. Run the Application:

    • Press F5 to run the application.
    • Navigate to http://localhost:port/Home/Index (adjust the port as necessary).
    • Open the Output window in Visual Studio to see the debug messages.
    OnActionExecuting - Before Action Method Executes
    OnActionExecuted - After Action Method Executes
    OnResultExecuting - Before Action Result Executes
    OnResultExecuted - After Action Result Executes
    

Step 4: Implement Built-in Action Filters

ASP.NET MVC provides several built-in action filters that cover common scenarios.

Step 4.1: [OutputCache]

  1. Modify the HomeController:

    • Apply the [OutputCache] attribute to the About action method.
    using System.Web.Mvc;
    using ActionFiltersExample.Filters;
    
    namespace ActionFiltersExample.Controllers
    {
        public class HomeController : Controller
        {
            [MyCustomActionFilter]
            public ActionResult Index()
            {
                return View();
            }
    
            [OutputCache(Duration = 60, VaryByParam = "none")]
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
        }
    }
    

Step 4.2: [Authorize]

  1. Create a Login View:

    • Right-click on the Views folder and create a new folder named Account.
    • Inside the Account folder, add a new view named Login.cshtml.
    @{
        ViewBag.Title = "Login";
    }
    
    <h2>@ViewBag.Title.</h2>
    <form method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required />
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required />
        <button type="submit">Login</button>
    </form>
    
  2. Create an Account Controller:

    • Right-click on the Controllers folder and add a new MVC 5 Controller - Empty named AccountController.
    using System.Web;
    using System.Web.Mvc;
    
    namespace ActionFiltersExample.Controllers
    {
        public class AccountController : Controller
        {
            [HttpPost]
            public ActionResult Login(string username, string password)
            {
                // For demonstration, always authenticate successfully
                FormsAuthentication.SetAuthCookie(username, false);
                return RedirectToAction("Index", "Home");
            }
    
            public ActionResult Logout()
            {
                FormsAuthentication.SignOut();
                return RedirectToAction("Index", "Home");
            }
        }
    }
    
  3. Modify the Web.config:

    • Enable forms authentication in Web.config.
    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="~/Account/Login" timeout="2880" />
      </authentication>
      ...
    </system.web>
    
  4. Add [Authorize] Filter:

    • Apply the [Authorize] attribute to the About action method.
    [Authorize]
    [OutputCache(Duration = 60, VaryByParam = "none")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
    
        return View();
    }
    
  5. Test the Authorization:

    • Navigate to http://localhost:port/Home/About.
    • You should be redirected to the Login page.
    • Enter any username and password, then submit the form.
    • You should now be able to access the About page.

Summary

 YOU NEED ANY HELP? THEN SELECT ANY TEXT.

Top 10 Interview Questions & Answers on ASP.NET MVC Action Filters and their Types

Top 10 Questions and Answers on ASP.NET MVC Action Filters and Their Types

1. What is an Action Filter in ASP.NET MVC?

2. What are the different types of Action Filters available in ASP.NET MVC?

Answer: The primary types of Action Filters in ASP.NET MVC are:

  • Attribute-based Action Filters: These are the most commonly used. They inherit from ActionFilterAttribute and are applied to controllers or action methods using attributes.
  • Global Action Filters: Defined in the Global.asax file, these apply to all action methods across the application unless overridden.
  • Interface-based Action Filters: Developers can create filters by implementing the IActionFilter interface directly.
  • Override-based Action Filters: These are created by deriving a class from Controller and overriding the OnActionExecuting and OnActionExecuted methods in the controller itself.

3. How do you implement an Attribute-based Action Filter in ASP.NET MVC?

Answer: To implement an Attribute-based Action Filter, you can create a class that inherits from ActionFilterAttribute and override the OnActionExecuting and OnActionExecuted methods as needed:

public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Before executing action logic
        filterContext.HttpContext.Response.Write("Before action executes<br>");
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // After executing action logic
        filterContext.HttpContext.Response.Write("After action executes<br>");
    }
}

You can then apply this filter to any action or controller using the [CustomActionFilter] attribute.

4. How do Global Action Filters differ from Attribute-based Action Filters?

Answer: Global Action Filters are registered in the Global.asax file within the RegisterGlobalFilters method. They are applied globally to every action method, unlike Attribute-based Action Filters, which must be manually added to each controller or specific action method to be applied:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new CustomActionFilter());
}

Global Action Filters provide a way to handle concerns that apply universally without the need for repetitive coding.

5. Can you explain how Interface-based Action Filters work in ASP.NET MVC?

Answer: Interface-based Action Filters allow you to create more flexible filters by implementing the IActionFilter interface directly, providing OnActionExecuting and OnActionExecuted methods. This method does not use any inheritance so it’s useful when you want to implement the filter differently compared to derived classes:

public class CustomActionFilter: IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Handle pre-action logic here
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Handle post-action logic here
    }
}

After implementation, you’d register it via Global.asax just like an Attribute-based filter.

6. How can you cancel the execution of an Action Method using an Action Filter?

Answer: In an OnActionExecuting method, you can set the Cancel property in the filterContext parameter to true, which prevents the action method from running:

public class CustomActionFilter: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Some condition to cancel
        if(conditionNotMet)
        {
            filterContext.Result = new RedirectResult("/Error");
            filterContext.Cancel = true;
        }
    }
}

Setting cancel=true is typically followed by assigning an appropriate ActionResult to the filterContext.Result.

7. When would you use Override-based Action Filters instead of Attribute-based ones?

Answer: Override-based Action Filters provide control over pre- and post-action processing at the controller level. This can be advantageous when you need specific filtering behavior tailored to a single controller rather than applying the same filter universally. However, this approach lacks reusability across multiple controllers compared to Attribute-based action filters.

8. Does an Action Filter also have access to the result object returned by an action method?

Answer: Yes, an Action Filter has access to the result object returned by an action method through the ActionExecutedContext parameter in the OnActionExecuted method. This means you can modify the result or log details about it:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var result = filterContext.Result;
    if(result is ViewResult)
    {
        filterContext.Controller.ViewBag.Message = "Modified by filter";
    }
}

This flexibility enables more intricate behaviors and data manipulation based on action results.

9. Can Action Filters change parameters passed to an action method or return results of action methods?

Answer: Yes, Action Filters can modify parameters passed to an action method using the ActionParameters property of ActionExecutingContext. Similarly, filters can modify the result returned by an action by changing Result in ActionExecutedContext:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(filterContext.ActionParameters.ContainsKey("id"))
    {
        filterContext.ActionParameters["id"] = 1; // Change parameter value
    }
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    filterContext.Result = new ContentResult() {Content = "Modified content by Filter"};
}

However, it is recommended to handle these modifications carefully as altering input parameters or output responses might lead to unexpected behaviors.

10. Are Action Filters executed in a specific order if multiple filters are applied?

Answer: Yes, when multiple Action Filters are applied to a single action or controller, they are executed in a specific order determined by their registration:

  1. Global Action Filters: Executed first, in the order they were added to the GlobalFilterCollection.
  2. Attribute-based Action Filters: Applied to a controller or an action method. Filters on the action method execute after controller-level filters, in the order they appear in the source code.
  3. Override-based Action Filters in Controller: Lastly, these filters run based on whether OnActionExecuting or OnActionExecuted is overridden in the controller or not.

This ordered execution ensures consistent behavior and predictable outcomes for filters interacting with each other.

You May Like This Related .NET Topic

Login to post a comment.