Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

How ASP.NET Core Builds Its Middleware Pipeline: The Reverse-Nesting Secret

This article explains how ASP.NET Core constructs its middleware pipeline by reverse-nesting RequestDelegate functions in IApplicationBuilder.Build(), causing requests to flow forward in registration order and responses to flow backward, which dictates why components like UseExceptionHandler must be registered first.

Middleware essence

Every middleware in ASP.NET Core is fundamentally a delegate of type RequestDelegate:

public delegate Task RequestDelegate(HttpContext context);

Each middleware component is a function that receives the next RequestDelegate in the chain and returns a new RequestDelegate that wraps its own logic around the next one — in other words, it receives the next middleware and returns the current middleware's handling delegate .

Pipeline construction in IApplicationBuilder.Build() IApplicationBuilder maintains an internal list of middleware delegates. Its Build() method constructs the final pipeline by iterating the list in reverse order and nesting each middleware around the accumulated delegate:

public RequestDelegate Build() {
    RequestDelegate app = context => {
        context.Response.StatusCode = 404;
        return Task.CompletedTask;
    };

    foreach (var middleware in _middlewares.Reverse()) {
        app = middleware(app);
    }

    return app;
}

This reverse-nesting guarantees that middleware executes in registration order during the request phase and in reverse order during the response phase .

Bidirectional flow

Request phase: flows from the first registered middleware to the last.

Response phase: flows from the last middleware back to the first.

Practical consequence: UseExceptionHandler must be first

Because the pipeline is bidirectional, UseExceptionHandler must be registered earliest. It needs to wrap the entire pipeline so its try/catch around await next() can capture exceptions from both the request phase (before next()) and the response phase (after next() returns). If placed later, exceptions from earlier middleware would escape its handler.

Final thought

Can you draw the execution-order diagram for your project's middleware pipeline? Understanding this construction mechanism is essential to truly mastering ASP.NET Core.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentMiddlewarePipelineASP.NET CoreIApplicationBuilderRequestDelegate

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion