Lesson 32: Middleware, Filters & Custom Attributes in ASP.NET
Intercept and transform HTTP requests with middleware pipelines, action filters, and custom attributes.
What You'll Learn
- • Custom middleware for logging, timing, and error handling
- • Action, result, and exception filters
- • Custom attributes for API keys and rate limiting
- • Middleware pipeline ordering and its importance
🧠 Real-World Analogy
Middleware is like airport security checkpoints. Every request (passenger) passes through them in order: ticket check → security scan → passport control → boarding. Each checkpoint can stop the request, modify it, or let it through. The order matters — you can't board before security.
Custom Middleware
Middleware sits in the HTTP pipeline and processes every request. Each middleware component calls _next(context) to pass the request to the next component. Code before _next runs on the request; code after runs on the response. Order matters — exception handling must come first.
Custom Middleware — Timing & Error Handling
Build middleware that times requests and catches unhandled exceptions.
// Middleware — intercepts every HTTP request/response
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
// Custom middleware class
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
public RequestTimingMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
// Add a request ID for tracing
...Action Filters
Filters are more targeted than middleware — they run only for specific controllers or actions. ASP.NET provides four filter types: Authorization, Action, Result, and Exception filters. They're ideal for cross-cutting concerns that don't apply to every request.
Action, Result & Exception Filters
Log actions, add response headers, and handle specific exceptions with filters.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
// Action Filter — runs before/after controller actions
public class LogActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
var action = context.ActionDescriptor.DisplayName;
var args = string.Join(", ", context.ActionArguments
.Select(kv => $"{kv.Key}={kv.Value}"));
Console.WriteLine($" 🔵 Before: {action}({args})");
}
publ
...Custom Attributes
Custom attributes combine filter logic with declarative syntax. Decorate controllers or actions with [RequireApiKey] or [RateLimit(10, 60)] to add security and throttling without cluttering business logic.
Custom Attributes — API Key & Rate Limiting
Build reusable attribute-based security and rate limiting.
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
// Custom attribute that validates API keys
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireApiKeyAttribute : Attribute, IAuthorizationFilter
{
private const string API_KEY_HEADER = "X-Api-Key";
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.Request.Headers
.TryGetValue(API_KEY_HEADER, out va
...| Concept | Scope | Use For |
|---|---|---|
| Middleware | Every request | Logging, CORS, compression, auth |
| Action Filter | Specific controllers/actions | Validation, audit logging |
| Exception Filter | Specific controllers/actions | Domain-specific error handling |
| Custom Attribute | Declarative (any target) | API keys, rate limits, caching |
Pro Tip
Use IEndpointFilter in Minimal APIs for the same functionality as action filters in controllers. They support DI and async, making them very flexible.
Common Mistakes
- • Placing exception middleware after UseAuthorization — errors in auth won't be caught
- • Using scoped services in middleware constructor — use
InvokeAsyncparameters instead - • Forgetting to call
_next(context)— request gets stuck
Lesson Complete!
You've mastered ASP.NET middleware, filters, and custom attributes. Next, dive into Entity Framework Core internals.
Sign up for free to track which lessons you've completed and get learning reminders.