ASP.NET Core  

ASP.NET Core Middleware Pipeline Explained

Introduction

In ASP.NET Core, one of the most important concepts to understand is the Middleware Pipeline. Every HTTP request and response in an ASP.NET Core application passes through a series of components called middleware.

Middleware plays a key role in handling requests, processing responses, managing authentication, logging, error handling, and much more. Understanding how the ASP.NET Core middleware pipeline works is essential for building scalable, secure, and high-performance web applications.

In this article, we will explain the ASP.NET Core middleware pipeline in simple words, how it works internally, and how you can use it effectively with real-world examples.

What is Middleware in ASP.NET Core?

Middleware is a piece of code that handles HTTP requests and responses.

In simple words, middleware is like a checkpoint in a pipeline where a request passes through multiple steps before reaching its final destination.

Each middleware component can:

  • Process the request

  • Pass it to the next middleware

  • Modify the response

  • Stop the request pipeline

What is Middleware Pipeline?

The middleware pipeline is a sequence of middleware components that are executed one after another.

When a request comes in:

  1. It enters the pipeline

  2. Passes through each middleware

  3. Reaches the endpoint (like a controller)

  4. Response travels back through the same pipeline

How Middleware Pipeline Works (Step-by-Step)

Step 1: Incoming Request

A client sends an HTTP request to the server.

Step 2: Middleware Execution Begins

The request enters the pipeline and hits the first middleware.

Step 3: Request Processing

Each middleware can:

  • Handle the request

  • Pass it forward using next()

Step 4: Endpoint Execution

The request reaches the endpoint (Controller, Razor Page, or Minimal API).

Step 5: Response Processing

The response flows back through the middleware in reverse order.

Visual Flow of Middleware Pipeline

Request → Middleware 1 → Middleware 2 → Middleware 3 → Endpoint → Middleware 3 → Middleware 2 → Middleware 1 → Response

Common Built-in Middleware in ASP.NET Core

1. UseRouting()

  • Matches incoming requests to endpoints

2. UseAuthentication()

  • Validates user identity

3. UseAuthorization()

  • Checks user permissions

4. UseStaticFiles()

  • Serves static files like images, CSS, JS

5. UseExceptionHandler()

  • Handles errors globally

Example of Middleware Pipeline in Program.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseExceptionHandler("/error");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Important Concept: Order of Middleware

Middleware order is very important in ASP.NET Core.

  • Middleware executes in the order they are added

  • Incorrect order can break the application

Example

  • Authentication must come before Authorization

Types of Middleware

1. Terminal Middleware

  • Does not call next middleware

  • Ends the pipeline

Example:

app.Run(async context =>
{
    await context.Response.WriteAsync("Hello World");
});

2. Non-Terminal Middleware

  • Calls next middleware using await next()

Example:

app.Use(async (context, next) =>
{
    Console.WriteLine("Before Request");

    await next();

    Console.WriteLine("After Response");
});

Creating Custom Middleware in ASP.NET Core

You can create your own middleware for custom logic.

Step 1: Create Middleware Class

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        Console.WriteLine("Request received");

        await _next(context);

        Console.WriteLine("Response sent");
    }
}

Step 2: Register Middleware

app.UseMiddleware<LoggingMiddleware>();

Middleware vs Filters in ASP.NET Core

FeatureMiddlewareFilters
ScopeGlobalController/Action level
ExecutionPipeline levelMVC pipeline
Use CaseLogging, auth, routingAction-specific logic

Real-World Example

In a real web application:

  • Request enters

  • Logging middleware logs request

  • Authentication checks user

  • Authorization validates access

  • Controller processes request

  • Response is sent back

This structured pipeline ensures performance and security.

Common Mistakes to Avoid

1. Wrong Middleware Order

Can break authentication or routing.

2. Not Calling next()

Stops pipeline unexpectedly.

3. Heavy Logic in Middleware

Can slow down application.

Best Practices for Middleware Pipeline

  • Keep middleware lightweight

  • Use correct order

  • Handle exceptions globally

  • Use custom middleware only when needed

  • Avoid blocking operations

Summary

The ASP.NET Core middleware pipeline is a powerful mechanism that processes every HTTP request and response. It allows developers to build flexible, scalable, and high-performance applications by organizing logic into reusable components. Understanding middleware order, execution flow, and best practices is essential for mastering ASP.NET Core development.