Every single HTTP request in an ASP.NET Core application travels through a pipeline before it ever reaches your controller or Razor page. Most developers use this pipeline every day — they call app.UseRouting(), app.UseAuthorization(), maybe throw in a custom one — but rarely stop to think about what's actually happening under the hood. When I first started with ASP.NET Core, I treated the Configure method as boilerplate I'd copy from templates. That was a mistake. Understanding middleware properly changes how you architect, debug, and optimize your applications. This guide covers it properly.

What is Middleware?

Middleware is a software component assembled into an application pipeline to handle HTTP requests and responses. Each component in the pipeline decides whether to pass the request on to the next component — and can perform work both before and after that handoff happens.

The key mental model: middleware forms a chain. A request enters the first component, which can do some work, then call the next component, which does its own work, and so on. On the way back out (the response), each component gets another chance to run code — in reverse order. Any component can also short-circuit the pipeline, meaning it handles the request entirely and never calls the next component at all.

Middleware in ASP.NET Core comes from three sources:

  • Built-in — shipped with the .NET runtime (authentication, routing, static files, etc.)
  • Third-party — installed via NuGet packages
  • Custom — written by your team for your specific needs

All middleware is registered in the Configure method of your Startup class (or directly in Program.cs in .NET 6+). Here's what a typical default setup looks like:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

Middleware Ordering — Why It Matters More Than You Think

Order is foundational. Middleware executes in the exact sequence you register it, and responses travel back through in reverse. Get the order wrong and you'll end up with authorization running before routing (so it has no idea what endpoint is being accessed), or static files being checked after authentication (so your CSS requires a login). I've seen teams spend hours debugging issues that were purely ordering problems.

Here's the recommended order for a standard ASP.NET Core application:

# Middleware Purpose Scope
1ExceptionHandlerCatches exceptions globallyAll
2HSTSEnforces HTTPS via headersProduction
3HttpsRedirectionRedirects HTTP to HTTPSAll
4StaticFilesServes CSS, JS, imagesAll
5RoutingMatches URLs to endpointsAll
6AuthorizationValidates user permissionsAll
7EndpointsExecutes matched endpointAll
💡 Think of the middleware pipeline as a tube. Requests enter from one end and travel through each component in order. Responses travel back in reverse. Every component gets two shots — once on the way in, once on the way out.

Run, Use, and Map — The Three Building Blocks

ASP.NET Core gives you three primary methods for wiring up middleware. Understanding the difference between them is where things start to click.

app.Run() — Terminal Middleware

app.Run() is a terminal delegate. It does not have a next parameter, which means it always ends the request pipeline. Nothing registered after a Run() will ever execute.

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

app.Use() — Chainable Middleware

app.Use() is the workhorse. It receives both the HttpContext and a next delegate. Calling await next() passes control to the next component in the pipeline. This is what lets you run code before and after downstream middleware.

In my experience, this is where most custom logic lives — logging, timing, header injection, you name it. Here's a concrete example showing execution order with two Use() calls and two Run() calls:

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Before Invoke from 1st app.Use()\n");
    await next();
    await context.Response.WriteAsync("After Invoke from 1st app.Use()\n");
});

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Before Invoke from 2nd app.Use()\n");
    await next();
    await context.Response.WriteAsync("After Invoke from 2nd app.Use()\n");
});

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello from 1st app.Run()\n");
});

// This second Run() will never be reached:
app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello from 2nd app.Run()\n");
});

The output for a request hitting this pipeline will be:

  1. Before Invoke from 1st app.Use()
  2. Before Invoke from 2nd app.Use()
  3. Hello from 1st app.Run()
  4. After Invoke from 2nd app.Use()
  5. After Invoke from 1st app.Use()

Notice how the "After" lines run in reverse order — that's the pipeline unwinding on the response path. The second Run() is dead code; the first one terminates the pipeline before it's ever reached.

app.Map() — Branch the Pipeline

app.Map() lets you branch the pipeline based on a URL path prefix. When a request matches the specified path, it goes down that branch and never reaches the main pipeline. This is useful for things like health check endpoints, admin routes, or versioned API paths.

app.Map("/m1", HandleMapOne);

app.Map("/m2", appMap => {
    appMap.Run(async context =>
    {
        await context.Response.WriteAsync("Hello from 2nd app.Map()");
    });
});

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

private static void HandleMapOne(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Hello from 1st app.Map()");
    });
}

Here's how different URLs route through this setup:

Request URL Response
https://localhost:44362/Hello from app.Run()
https://localhost:44362/m1Hello from 1st app.Map()
https://localhost:44362/m1/xyzHello from 1st app.Map()
https://localhost:44362/m2Hello from 2nd app.Map()
https://localhost:44362/m500Hello from app.Run()

Worth noting: /m1/xyz still hits the /m1 branch because Map() matches on path prefix, not exact path. That's a subtle but important detail.

Writing Custom Middleware

Inline lambdas are fine for quick experiments, but for anything you'd actually ship to production, you want a proper middleware class. It's cleaner, testable, and plays nicely with dependency injection.

A custom middleware class needs three things:

  • A constructor that accepts a RequestDelegate (the next middleware)
  • An InvokeAsync(HttpContext) method
  • Optionally, an extension method on IApplicationBuilder for clean registration

Here's a real-world example — a URL logging middleware that logs every incoming request URL using the built-in ILogger:

public class LogURLMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<LogURLMiddleware> _logger;

    public LogURLMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory?.CreateLogger<LogURLMiddleware>()
            ?? throw new ArgumentNullException(nameof(loggerFactory));
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _logger.LogInformation($"Request URL: {UriHelper.GetDisplayUrl(context.Request)}");
        await this._next(context);
    }
}

And the extension method that makes registration feel native:

public static class LogURLMiddlewareExtensions
{
    public static IApplicationBuilder UseLogUrl(this IApplicationBuilder app)
    {
        return app.UseMiddleware<LogURLMiddleware>();
    }
}

Register it in Configure just like any built-in middleware:

app.UseLogUrl();

The extension method pattern is worth the extra few lines. It keeps your Configure method readable and hides the generic UseMiddleware<T>() call behind a meaningful name. When someone reads app.UseLogUrl(), they know exactly what it does.

Directory Browsing

One middleware that often gets overlooked — or misused — is UseDirectoryBrowser. It enables file listing for a specified folder, letting users browse directory contents through the browser. It's disabled by default, and for good reason.

Here's how to enable it for a specific path:

app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
    RequestPath = "/images"
});
⚠️ Security warning: Never enable directory browsing on production servers without a very specific reason. Exposing your file structure gives attackers a roadmap to your application. If you need it for internal tooling, restrict it behind authentication middleware registered before UseDirectoryBrowser.

Wrapping Up

Middleware is one of those topics that seems simple on the surface — just a list of app.Use*() calls — but has real depth once you start digging. Getting the ordering right, knowing when to use Run vs Use vs Map, and writing clean custom middleware classes are skills that separate developers who just make things work from developers who understand why they work.

In my experience, the teams that invest time understanding the pipeline early on spend far less time debugging mysterious request-handling bugs later. Start with the built-ins, understand their order, then layer in your custom components with intention. Your future self — and your teammates — will thank you.

Related Articles