0Pricing
C# Academy · Lesson

ASP.NET Core Pipeline Overview

Understand how requests flow through the middleware pipeline, HttpContext, and how responses are built up.

ASP.NET Core Pipeline Overview is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Request Pipeline

Every HTTP request in ASP.NET Core flows through a middleware pipeline. Each piece of middleware can inspect, modify, short-circuit, or forward the request to the next component. Understanding this pipeline is fundamental to building ASP.NET Core apps.

HttpContext: The Request Envelope

HttpContext carries everything about a request and response: headers, cookies, body, user claims, connection info, and the cancellation token. All middleware operates on it.

app.Use(async (context, next) =>
{
    // Read request info
    var method  = context.Request.Method;
    var path    = context.Request.Path;
    var headers = context.Request.Headers;
    var user    = context.User.Identity?.Name;

    // Write to response
    context.Response.Headers.Append("X-Processed-By", "MyMiddleware");

    await next(context); // forward to next middleware
});

Middleware Registration Order

Middleware runs in the order it is registered. The response unwraps in reverse order (like a stack). Order is critical: authentication must run before authorization; routing before endpoint matching.

// Typical order for an ASP.NET Core app:
app.UseExceptionHandler("/error"); // outermost — catches everything
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("policy");
app.UseAuthentication();  // must be before Authorization
app.UseAuthorization();
app.UseRateLimiter();
app.UseOutputCache();
// MapHub, MapControllers, MapGet etc.
app.Run();

Use, Run, and Map

Three methods add middleware: Use (calls next), Run (terminal, never calls next), and Map (branches based on path).

// Use: passes to next
app.Use(async (ctx, next) =>
{
    Console.WriteLine("Before");
    await next(ctx);
    Console.WriteLine("After");
});

// Run: terminal — no next
app.Run(async ctx =>
    await ctx.Response.WriteAsync("Terminal"));

// Map: branch on path prefix
app.Map("/api", apiApp =>
    apiApp.Run(async ctx =>
        await ctx.Response.WriteAsync("API branch")));

Request and Response Bodies

Request and response bodies are streams. Reading the request body is one-time — enable request body buffering if you need to read it multiple times (e.g., in multiple middleware).

app.Use(async (ctx, next) =>
{
    // Enable buffering so body can be read multiple times
    ctx.Request.EnableBuffering();

    using var reader = new StreamReader(
        ctx.Request.Body,
        leaveOpen: true);
    var body = await reader.ReadToEndAsync();
    ctx.Request.Body.Position = 0; // rewind for next middleware

    Console.WriteLine($"Body: {body}");
    await next(ctx);
});

Short-Circuiting the Pipeline

Middleware can short-circuit by writing the response and NOT calling next. Useful for authentication gates, health checks, or maintenance pages.

app.Use(async (ctx, next) =>
{
    if (ctx.Request.Path == "/maintenance")
    {
        ctx.Response.StatusCode = 503;
        await ctx.Response.WriteAsync("Service under maintenance");
        return; // short-circuit — next is NOT called
    }
    await next(ctx);
});

The IMiddleware Interface

For class-based middleware that needs DI, implement IMiddleware. Register the implementation in DI and use app.UseMiddleware<T>().

public class RequestTimingMiddleware : IMiddleware
{
    private readonly ILogger<RequestTimingMiddleware> _logger;
    public RequestTimingMiddleware(ILogger<RequestTimingMiddleware> l) => _logger = l;

    public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        await next(ctx);
        _logger.LogInformation("{Method} {Path}: {Ms}ms",
            ctx.Request.Method, ctx.Request.Path, sw.ElapsedMilliseconds);
    }
}

// Register:
builder.Services.AddTransient<RequestTimingMiddleware>();
app.UseMiddleware<RequestTimingMiddleware>();

Conventional Middleware Classes

Alternatively, create a class with an InvokeAsync(HttpContext, RequestDelegate) method. The framework injects dependencies (including the next delegate) via the constructor.

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _key;

    // RequestDelegate injected by framework
    public ApiKeyMiddleware(RequestDelegate next, IConfiguration cfg)
    {
        _next = next;
        _key = cfg["ApiKey"] ?? "";
    }

    public async Task InvokeAsync(HttpContext ctx)
    {
        if (ctx.Request.Headers["X-Api-Key"] != _key)
        {
            ctx.Response.StatusCode = 401;
            return;
        }
        await _next(ctx);
    }
}

Modifying Responses After Next

Code after await next(ctx) runs after the response starts being written. You can add response headers before next, but you cannot modify the status code or body after it.

app.Use(async (ctx, next) =>
{
    // Before: add response headers (safe)
    ctx.Response.OnStarting(() =>
    {
        ctx.Response.Headers.Append("X-Request-Id",
            Guid.NewGuid().ToString("N"));
        return Task.CompletedTask;
    });

    await next(ctx);

    // After: response may already be sent
    // SAFE: logging, metrics
    // UNSAFE: changing status code or writing body
    Console.WriteLine($"Response status: {ctx.Response.StatusCode}");
});

Real-World: Correlation ID Middleware

A production correlation ID middleware that adds a trace ID to every request for distributed tracing and logging.

public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;
    private const string Header = "X-Correlation-Id";

    public CorrelationIdMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext ctx)
    {
        var correlationId = ctx.Request.Headers[Header].FirstOrDefault()
            ?? Guid.NewGuid().ToString("N");

        ctx.Items["CorrelationId"] = correlationId;

        ctx.Response.OnStarting(() =>
        {
            ctx.Response.Headers.Append(Header, correlationId);
            return Task.CompletedTask;
        });

        using (Serilog.Context.LogContext.PushProperty("CorrelationId", correlationId))
            await _next(ctx);
    }
}

Quick Check

What is the difference between app.Use() and app.Run() when adding middleware?

Recap: ASP.NET Core Pipeline Overview

Key takeaways:

  • Middleware runs in registration order; responses unwind in reverse
  • Use → calls next; Run → terminal; Map → path-based branch
  • HttpContext contains request, response, user, cancellation token
  • Enable buffering to read the request body multiple times
  • IMiddleware interface enables DI-friendly class-based middleware
  • Add response headers via OnStarting(); don't change status after next

Frequently asked questions

Is the “ASP.NET Core Pipeline Overview” lesson free?

Yes — the full text of “ASP.NET Core Pipeline Overview” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “ASP.NET Core Pipeline Overview”?

Understand how requests flow through the middleware pipeline, HttpContext, and how responses are built up. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “ASP.NET Core Pipeline Overview” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. ASP.NET Core Pipeline Overview
  2. Writing Custom Middleware
  3. Short-Circuiting & Branching
  4. Middleware Ordering & Built-in Middleware
← Back to C# Academy