ASP.NET Core  

ASP.NET Core Request Pipeline Explained with Real Examples

Introduction

Every HTTP request sent to an ASP.NET Core application follows a specific path before reaching your controller or API endpoint. Along the way, the request passes through several components that can inspect, modify, or even stop it before a response is returned.

This sequence of components is called the ASP.NET Core Request Pipeline.

Understanding how the request pipeline works is essential for every .NET developer. Whether you're building a Web API, an MVC application, or a Minimal API, knowing how requests are processed helps you write better middleware, improve application performance, and troubleshoot issues more effectively.

In this article, we'll explore how the ASP.NET Core request pipeline works, understand the role of middleware, and walk through practical examples.

What Is the ASP.NET Core Request Pipeline?

The request pipeline is a chain of middleware components that process every incoming HTTP request.

When a client sends a request:

  1. The request enters the application.

  2. It passes through each configured middleware.

  3. Middleware can inspect or modify the request.

  4. The request reaches the endpoint if no middleware stops it.

  5. The response travels back through the same middleware in reverse order.

Think of the pipeline as a production line where each middleware performs a specific task before passing the request to the next component.

Understanding Middleware

Middleware is software that sits between the incoming request and the outgoing response.

Each middleware can:

  • Read the request

  • Modify request data

  • Perform authentication

  • Log requests

  • Handle exceptions

  • Generate a response

  • Pass control to the next middleware

A middleware can either continue the pipeline or stop it by returning a response immediately.

A Simple Request Pipeline

The following example creates two middleware components.

var app = builder.Build();

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

    await next();

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

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

    await next();
});

app.MapGet("/", () => "Hello from ASP.NET Core!");

app.Run();

When a request is made, the output is:

Request received
Processing request
Response sent

Notice that the first middleware executes before and after the second middleware. This happens because the response travels back through the pipeline after the endpoint finishes processing.

Common Middleware in ASP.NET Core

Most ASP.NET Core applications use several built-in middleware components.

Some of the most common ones include:

  • Exception Handling

  • HTTPS Redirection

  • Static Files

  • Routing

  • Authentication

  • Authorization

  • Response Compression

  • CORS

  • Endpoint Mapping

Each middleware has a specific responsibility, making the application easier to maintain and extend.

Why Middleware Order Matters

The order in which middleware is added is extremely important.

For example, authentication should run before authorization.

Correct order:

app.UseAuthentication();

app.UseAuthorization();

Incorrect order:

app.UseAuthorization();

app.UseAuthentication();

If authorization runs first, the user hasn't been authenticated yet, causing authorization to fail.

Similarly, routing must be configured before endpoint execution.

Always review middleware order carefully, as incorrect ordering is one of the most common causes of unexpected behavior.

Handling Exceptions

A global exception handler prevents application crashes and returns consistent error responses.

app.UseExceptionHandler("/error");

Instead of exposing internal exception details to users, the application returns a controlled response while logging the actual error for troubleshooting.

This improves both security and user experience.

Adding Custom Middleware

Creating custom middleware is straightforward.

The following middleware measures how long each request takes to process.

app.Use(async (context, next) =>
{
    var start = DateTime.UtcNow;

    await next();

    var duration = DateTime.UtcNow - start;

    Console.WriteLine($"Request completed in {duration.TotalMilliseconds} ms");
});

This technique is useful for logging, monitoring, auditing, and performance analysis.

Real-World Request Flow

Consider an e-commerce application.

A request to view products might follow this path:

  1. Request arrives at the server.

  2. Exception handling middleware starts.

  3. HTTPS redirection checks the protocol.

  4. Routing identifies the matching endpoint.

  5. Authentication verifies the user's identity.

  6. Authorization checks access permissions.

  7. Custom logging middleware records the request.

  8. The Products API executes.

  9. The response travels back through the middleware.

  10. The client receives the response.

Each middleware performs a specific task without interfering with the others.

Tips for Building an Efficient Pipeline

A well-designed pipeline improves both performance and maintainability.

Keep these points in mind:

  • Add only the middleware your application needs.

  • Place lightweight middleware near the beginning of the pipeline.

  • Use authentication before authorization.

  • Handle exceptions globally instead of using multiple try-catch blocks.

  • Keep custom middleware focused on a single responsibility.

  • Avoid performing expensive operations unless necessary.

  • Log important requests without logging sensitive information.

Following these practices helps keep your application fast and easy to troubleshoot.

Best Practices

When working with the ASP.NET Core request pipeline:

  • Understand the purpose of every middleware before adding it.

  • Carefully configure middleware in the correct order.

  • Use built-in middleware whenever possible.

  • Write reusable custom middleware for common functionality.

  • Measure request performance to identify bottlenecks.

  • Keep middleware lightweight and focused.

  • Test the pipeline after introducing new middleware.

  • Review logging to ensure it provides useful diagnostic information without exposing sensitive data.

Conclusion

The ASP.NET Core request pipeline is one of the most important concepts every .NET developer should understand. Every request and response passes through this pipeline, making middleware a powerful way to add functionality such as authentication, logging, exception handling, and performance monitoring.

By understanding how middleware works and configuring it in the correct order, you can build applications that are secure, efficient, and easy to maintain. Whether you're creating a simple Web API or a large enterprise application, mastering the request pipeline will help you write cleaner code and troubleshoot issues with greater confidence.