Filters & Middleware in ASP.NET Core

Middleware = pipeline for every request. Filters = pipeline for MVC actions only.

60-Second Version: Middleware runs for all requests: logging, auth, static files. Filters run only after routing hits a controller: validate, cache, handle errors. Middleware wraps Filters.

1. Middleware: The Request Pipeline

Configured in Program.cs. Order matters.

var app = builder.Build();

app.UseExceptionHandler("/Home/Error"); // 1. Catch exceptions
app.UseStaticFiles(); // 2. Serve wwwroot files
app.UseRouting(); // 3. Match URL to endpoint
app.UseAuthentication(); // 4. Who are you?
app.UseAuthorization(); // 5. Are you allowed?
app.MapControllerRoute( // 6. Run MVC
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Request goes down. Response comes back up. Each middleware can short-circuit.

2. Filters: MVC-Specific Logic

Attributes on controllers or actions. Run after UseRouting picks an action.

Filter TypeRuns WhenExample
[Authorize]Before actionBlock guests
[HttpPost]During routingOnly allow POST
[ValidateAntiForgeryToken]Before POST actionPrevent CSRF
[ResponseCache]After actionCache output 60s
[ServiceFilter]Custom logicLog to DB

3. Filter Pipeline Order

5 types, run in fixed order:

1. Authorization Filters โ†’ [Authorize] Can user run this?
2. Resource Filters โ†’ [ResponseCache] Runs before/after all else
3. Action Filters โ†’ [ServiceFilter] Runs before/after action method
4. Exception Filters โ†’ [HandleError] Catch unhandled exceptions
5. Result Filters โ†’ [OutputCache] Runs before/after IActionResult executes

4. Custom Action Filter

public class LogActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Runs BEFORE action
        Console.WriteLine($"Starting {context.ActionDescriptor.DisplayName}");
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Runs AFTER action
        Console.WriteLine($"Finished with {context.Result}");
    }
}

// Register: builder.Services.AddScoped<LogActionFilter>();
// Use: [ServiceFilter(typeof(LogActionFilter))]
public class ProductController : Controller { }
Beginner Trap: Priya puts app.UseAuthorization(); before app.UseRouting();. Auth fails because routing hasn't set endpoint yet. Order: Exception โ†’ StaticFiles โ†’ Routing โ†’ Auth โ†’ Endpoints.

Quick Check ๐Ÿง 

Next: Partial Views & View Components - Reusable UI chunks.

Comments on Tag Helpers (0)

No comments yet. Be the first to share your thoughts!