The ActionFilterAttribute is a base class in ASP.NET MVC that allows developers to create custom action filters. Action filters are used to execute code before or after an action method runs, providing a way to add cross-cutting concerns such as logging, authentication, authorization, caching, and error handling to your application. By using action filters, you can encapsulate common functionality that can be reused across multiple controllers and action methods.

Key Features of Action Filters

Action filters provide several key features:

  • Pre-Processing: Code can be executed before an action method is called, allowing you to perform tasks such as validation or logging.
  • Post-Processing: Code can be executed after an action method has completed, enabling you to modify the result or perform additional actions.
  • Reusable Logic: Action filters can be applied to multiple action methods or controllers, promoting code reuse and reducing duplication.
  • Built-in Filters: ASP.NET MVC provides several built-in action filters, such as AuthorizeAttribute, OutputCacheAttribute, and HandleErrorAttribute.

Creating a Custom Action Filter

To create a custom action filter, you need to inherit from the ActionFilterAttribute class and override the appropriate methods. Below is an example of a custom action filter that logs the execution time of action methods:

        
using System.Diagnostics;
using System.Web.Mvc;

public class LogExecutionTimeAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Start timing
filterContext.HttpContext.Items["StartTime"] = Stopwatch.StartNew();
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Stop timing
var stopwatch = (Stopwatch)filterContext.HttpContext.Items["StartTime"];
stopwatch.Stop();
var executionTime = stopwatch.ElapsedMilliseconds;

// Log the execution time (for demonstration, we will just write to the console)
System.Diagnostics.Debug.WriteLine($"Action executed in {executionTime} ms");
}
}

In this example:

  • The LogExecutionTimeAttribute class inherits from ActionFilterAttribute.
  • The OnActionExecuting method is overridden to start a stopwatch before the action method executes.
  • The OnActionExecuted method is overridden to stop the stopwatch after the action method completes and log the execution time.

Applying the Custom Action Filter

You can apply the custom action filter to a controller or an individual action method using the [LogExecutionTime] attribute. Below is an example of how to apply it to an action method:

        
public class HomeController : Controller
{
[LogExecutionTime]
public ActionResult Index()
{
// Simulate some processing
System.Threading.Thread.Sleep(500);
return View();
}
}

In this example, the LogExecutionTime attribute is applied to the Index action method of the HomeController. When the action method is called, the execution time will be logged to the console.

Conclusion

The ActionFilterAttribute in ASP.NET MVC is a powerful tool for implementing cross-cutting concerns in your application. By creating custom action filters, you can encapsulate reusable logic that can be applied to multiple action methods or controllers. This promotes cleaner code, better organization, and easier maintenance. Understanding how to use action filters effectively can greatly enhance the functionality and performance of your ASP.NET MVC applications.