A Complete Guide - ASP.NET MVC Action Filters and their Types
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:
- Authorization Filter – Determines whether the user is authorized to execute the action.
- Action Filter – Pre-action and post-action execution.
- Action Method – Executes the specified action.
- Result Filter – Handles the output processing before the action result is executed.
- 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:
ActionFilterAttribute: The base class for action filters. It provides the
OnActionExecuting
andOnActionExecuted
methods for you to override.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 }
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 }
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
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
- Open Visual Studio
- Create a New Project:
- Go to
File
>New
>Project
- Select
ASP.NET Web Application (.NET Framework)
- Name your project
ActionFiltersExample
and clickCreate
- Go to
- Select Template:
- Choose
MVC
from the available templates and clickCreate
- Choose
Step 2: Create Action Filters
Action Filters can be categorized into two main types:
- OnActionExecuting: This method executes before the action method is called.
- 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
Create a Filter Folder:
- Right-click on the project in the Solution Explorer.
- Select
Add
>New Folder
and name itFilters
.
Create an Action Filter Class:
- Right-click on the
Filters
folder in the Solution Explorer. - Select
Add
>New Item
. - Select
Class
and name itMyCustomActionFilter.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"); } } }
- Right-click on the
Step 3.2: Use the Custom Action Filter
Modify the HomeController:
- Open the
HomeController
class located in theControllers
folder. - Apply the
MyCustomActionFilter
attribute to theIndex
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(); } } }
- Open the
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
- Press
Step 4: Implement Built-in Action Filters
ASP.NET MVC provides several built-in action filters that cover common scenarios.
Step 4.1: [OutputCache]
Modify the HomeController:
- Apply the
[OutputCache]
attribute to theAbout
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(); } } }
- Apply the
Step 4.2: [Authorize]
Create a Login View:
- Right-click on the
Views
folder and create a new folder namedAccount
. - Inside the
Account
folder, add a new view namedLogin.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>
- Right-click on the
Create an Account Controller:
- Right-click on the
Controllers
folder and add a newMVC 5 Controller - Empty
namedAccountController
.
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"); } } }
- Right-click on the
Modify the Web.config:
- Enable forms authentication in
Web.config
.
<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> ... </system.web>
- Enable forms authentication in
Add [Authorize] Filter:
- Apply the
[Authorize]
attribute to theAbout
action method.
[Authorize] [OutputCache(Duration = 60, VaryByParam = "none")] public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); }
- Apply the
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.
- Navigate to
Summary
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 theOnActionExecuting
andOnActionExecuted
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:
- Global Action Filters: Executed first, in the order they were added to the
GlobalFilterCollection
. - 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.
- Override-based Action Filters in Controller: Lastly, these filters run based on whether
OnActionExecuting
orOnActionExecuted
is overridden in the controller or not.
This ordered execution ensures consistent behavior and predictable outcomes for filters interacting with each other.
Login to post a comment.