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 Type | Runs When | Example |
|---|---|---|
[Authorize] | Before action | Block guests |
[HttpPost] | During routing | Only allow POST |
[ValidateAntiForgeryToken] | Before POST action | Prevent CSRF |
[ResponseCache] | After action | Cache output 60s |
[ServiceFilter] | Custom logic | Log 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.
No comments yet. Be the first to share your thoughts!