design

Middleware in .NET Core: The Pipeline Powerhouse

April 11, 2025

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!


🔥 What is Middleware?

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."


🔄 How the Middleware Pipeline Works

  1. Request comes in → First middleware processes it
  2. Middleware calls next() → Passes control to the next one
  3. Response travels back → Each middleware can modify it
  4. Final response sent → After all middleware runs


💻 Built-in Middleware Examples

.NET Core includes essential middleware out of the box:

  • UseRouting() → Matches requests to endpoints
  • UseAuthentication() → Handles user auth
  • UseStaticFiles() → Serves static files (HTML, CSS, JS)
  • UseExceptionHandler() → Catches errors globally

🚀 Creating Custom Middleware


Let’s build a simple logging middleware:

Option 1: Inline Middleware (Simple)

app.Use(async (context, next) =>
{
    Console.WriteLine($"Request: {context.Request.Path}");
    await next(); // Pass to next middleware
    Console.WriteLine($"Response: {context.Response.StatusCode}");
});


Option 2: Class-Based (Reusable)

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>();


⚡ Middleware Execution Order Matters!

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 = 💥)


🔧 Real-World Use Cases

✅ Logging requests/responses

✅ Rate limiting API calls

✅ Custom authentication flows

✅ Request/response modification (e.g., adding headers)

✅ Feature flags (enable/disable endpoints dynamically)


🎯 Key Takeaways

✔ 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:

  • Adds a X-Request-Time header
  • Blocks requests from certain IPs
  • Measures request duration


📚 Learn More


Need help with a specific middleware scenario? Ask below! 👇

7 + 7 =