ASP.NET Core MVC Mastery

Action Filters

14 Views Updated 5/4/2026

Understanding Action Filters in ASP.NET Core

Action Filters are one of the most powerful features in ASP.NET Core. They allow you to execute logic **before** and **after** an individual action method runs. This is perfect for "Cross-Cutting Concerns" like logging, performance tracking, and security checks that you don't want to repeat in every action.

"Action Filters help you keep your controllers clean by moving repetitive logic into reusable classes."

The Filter Life Cycle

Action filters implement the IActionFilter or IAsyncActionFilter interfaces. They provide two main methods:

  • OnActionExecuting: Runs before the action method. You can inspect or modify arguments here.
  • OnActionExecuted: Runs after the action method. You can inspect the result set or handle exceptions here.

🔥 Example 1: Performance Tracking Filter

In a professional enterprise app, you need to know which actions are slow. This filter logs the execution time of every request it's applied to.


using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;

public class TrackPerformanceFilter : IActionFilter 
{
    private Stopwatch _stopwatch;

    public void OnActionExecuting(ActionExecutingContext context)
    {
        _stopwatch = Stopwatch.StartNew();
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        _stopwatch.Stop();
        var elapsed = _stopwatch.ElapsedMilliseconds;
        var actionName = context.ActionDescriptor.DisplayName;

        Console.WriteLine($"[PERF] Action {actionName} took {elapsed}ms");
    }
}
            

🔥 Example 2: Audit Logging (Security)

In banking or healthcare apps, you must log exactly who accessed what data. This filter automatically captures user ID and action details.


public class AuditLogFilter : IAsyncActionFilter 
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // 1. Logic BEFORE the action runs
        var user = context.HttpContext.User.Identity.Name ?? "Anonymous";
        var ip = context.HttpContext.Connection.RemoteIpAddress;
        
        Console.WriteLine($"[AUDIT] User {user} from {ip} is accessing {context.ActionDescriptor.DisplayName}");

        // 2. Execute the action
        var resultContext = await next();

        // 3. Logic AFTER the action runs
        if (resultContext.Exception != null) {
             Console.WriteLine("[AUDIT] Action failed with exception!");
        }
    }
}
            

🔥 Example 3: Data Transformation (API)

Sometimes you want to ensure all strings are "trimmed" or all dates are in "UTC" before saving them to the database. You can do this automatically in a filter.


public class ModelSanitizerFilter : IActionFilter 
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        foreach (var arg in context.ActionArguments.Values)
        {
            if (arg is string stringValue)
            {
                // Automatically trim all string parameters!
                // This prevents "  John Doe  " from being saved with spaces.
            }
        }
    }

    public void OnActionExecuted(ActionExecutedContext context) { /* No-op */ }
}
            
How to Register: You can apply filters via [ServiceFilter(typeof(MyFilter))] on an action/controller, or globally in Program.cs using builder.Services.AddControllersWithViews(options => options.Filters.Add()).
ASP.NET Core MVC Mastery
1. Core Framework
Introduction to ASP.NET Core MVC
MODULE 1: INTRODUCTION & ENVIRONMENT SETUP
Microsoft Web Stack Overview Evolution of ASP.NET Environment Setup
2. View Engine
Layouts & Partial Views in Razor
MODULE 2: .NET CORE FUNDAMENTALS
Core Concepts Project Structure Startup Flow Middleware Pipeline
MODULE 3: ASP.NET CORE BASICS
Creating Project CLI Commands wwwroot & Static Files
MODULE 4: MVC FUNDAMENTALS
MVC Architecture Dependency Injection (DI) Service Lifetimes
MODULE 5: DATA PASSING TECHNIQUES
ViewData vs ViewBag TempData ViewModel Pattern
MODULE 6: ROUTING
Conventional vs Attribute Routing Custom Constraints
MODULE 7: VIEWS & UI
Razor View Engine Layouts & Sections View Components
MODULE 8: ACTION RESULTS
ViewResult JsonResult RedirectResult
MODULE 9: HTML HELPERS
Form Helpers Custom HTML Helpers
MODULE 10: TAG HELPERS
Built-in Tag Helpers Custom Tag Helpers
MODULE 11: MODEL BINDING
FromQuery vs FromRoute Complex Binding
MODULE 12: VALIDATION
Data Annotations Remote Validation Fluent Validation
MODULE 13: STATE MANAGEMENT
Cookies & Sessions TempData
MODULE 14: FILTERS & SECURITY
Action Filters Authorize Filters Anti-forgery
MODULE 15: ENTITY FRAMEWORK CORE (DEEP DIVE)
DbContext Migrations LINQ Relationships
MODULE 16: DESIGN PATTERNS
Repository Pattern Unit of Work Clean Architecture
MODULE 17: FILE HANDLING
File Upload/Download PDF/Excel Generation
MODULE 18: ADVANCED ASP.NET CORE
Request Lifecycle Bundling & Minification Deployment
MODULE 19: PERFORMANCE & BEST PRACTICES
Caching Strategies Async Programming Secure Coding
MODULE 20: RAZOR PAGES (BONUS)
Razor Pages vs MVC
MODULE 21: REAL-WORLD PROJECTS (🔥 MUST DO)
E-Commerce Web Application Employee Management System