Middleware is the secret sauce behind every .NET Core web application. It handles requests, processes responses, and glues everything together. Let’s break it down—what it is, how it works, and how to use it like a pro!
Middleware is software components that sit in the request-response pipeline. Each middleware:
✔ Processes incoming requests
✔ Modifies responses
✔ Decides whether to pass control to the next middleware
✔ Can short-circuit the pipeline (like authentication blocks)
"Think of middleware as a chain of responsibility—each link handles a specific task."
next()
→ Passes control to the next one.NET Core includes essential middleware out of the box:
UseRouting()
→ Matches requests to endpointsUseAuthentication()
→ Handles user authUseStaticFiles()
→ Serves static files (HTML, CSS, JS)UseExceptionHandler()
→ Catches errors globallyLet’s build a simple logging middleware:
app.Use(async (context, next) => { Console.WriteLine($"Request: {context.Request.Path}"); await next(); // Pass to next middleware Console.WriteLine($"Response: {context.Response.StatusCode}"); });
public class LoggingMiddleware { private readonly RequestDelegate _next; public LoggingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { Console.WriteLine($"Request: {context.Request.Path}"); await _next(context); Console.WriteLine($"Response: {context.Response.StatusCode}"); } } // Register in Startup.cs app.UseMiddleware<LoggingMiddleware>();
Order is critical! Middleware runs in the order they're added:
app.UseExceptionHandler(); // 1️⃣ Catch errors early app.UseHttpsRedirection(); // 2️⃣ Force HTTPS app.UseStaticFiles(); // 3️⃣ Serve static files app.UseRouting(); // 4️⃣ Route requests app.UseAuthentication(); // 5️⃣ Check auth app.UseAuthorization(); // 6️⃣ Verify permissions app.UseEndpoints(...); // 7️⃣ Execute endpoint
⚠️ Gotcha: Misordered middleware can break your app! (Example: Auth before Routing = 💥)
✅ Logging requests/responses
✅ Rate limiting API calls
✅ Custom authentication flows
✅ Request/response modification (e.g., adding headers)
✅ Feature flags (enable/disable endpoints dynamically)
✔ Middleware = Pipeline components handling HTTP requests
✔ Order matters—add carefully!
✔ Built-in middleware covers common scenarios
✔ Custom middleware = endless flexibility
"Master middleware, and you master .NET Core’s HTTP pipeline."
👉 Try it! Build middleware that:
X-Request-Time
headerNeed help with a specific middleware scenario? Ask below! 👇