Skip to content

5.4 — Inline Custom Middleware

← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.3 Use, Run, Map · Next: 5.5 Conventional middleware

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

Inline middleware is middleware written as a lambda directly in Program.cs, rather than as its own class.

  • Written with app.Use(async (context, next) => { ... }).
  • Good for something small, obvious and unlikely to grow — adding a header, a quick check.
  • Once it needs dependencies, unit tests, or more than a few lines, move it to a class (5.5).

Definitions

Term What it is What it means
Inline middleware a lambda in Program.cs Middleware defined at the point of registration rather than in its own type.
app.Use(...) an extension method Takes a lambda receiving HttpContext and next.
context an HttpContext This request and response. See 5.8.
next a delegate The rest of the pipeline. Two overloads exist — Func<Task> and RequestDelegate.
RequestDelegate overload the newer form (.NET 7+) next takes the context. Avoids a per-request closure allocation.
Func<Task> overload the older form next() takes nothing. Allocates a closure per request.
context.RequestServices a property The DI container for this request. How inline middleware gets scoped services.
OnStarting a method on the response Registers a callback that runs just before the response is sent.

The concept

Why inline exists

Not every piece of middleware deserves a file. Adding one response header is three lines, and a class with a constructor, an InvokeAsync method and an extension method is more ceremony than the logic warrants.

Inline middleware lets you write it where it is registered:

app.Use(async (context, next) =>
{
    context.Response.Headers["X-App-Version"] = "1.4.2";
    await next();
});

That is complete and readable, and it sits exactly where someone reading Program.cs will look for it.

A picture: a sticky note versus a filing cabinet. A sticky note is perfect for one short reminder. It is the wrong home for a contract.

The line to draw

Move to a class when any of these becomes true:

  • It needs an injected dependency other than through RequestServices
  • It is more than roughly ten lines
  • You want to unit test it
  • The same logic is needed in more than one place
  • Program.cs is getting hard to scan

The last one matters more than people expect. Program.cs is the file where the whole application's shape is visible (4.3). Two hundred lines of inline lambdas destroys that.


How it works

The simple version

app.Use(async (context, next) =>
{
    // ── before: on the way in ──
    var start = Stopwatch.GetTimestamp();

    await next();          // run the rest of the pipeline

    // ── after: on the way back out ──
    var ms = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
    Console.WriteLine($"{context.Request.Path} took {ms:F1}ms");
});

The structure is always the same: work, await next(), more work. Either half can be empty.

The two overloads

// Older — next is Func<Task>, called with no arguments
app.Use(async (context, next) =>
{
    await next();
});

// Newer (.NET 7+) — next is RequestDelegate, called with the context
app.Use(async (HttpContext context, RequestDelegate next) =>
{
    await next(context);
});

The newer form avoids allocating a closure object on every request. In middleware that runs for every single request, that allocation is real GC pressure (3.4) — worth using in anything hot, and irrelevant in something that runs occasionally.

Note the explicit type annotations. Without them the compiler picks the older overload.

⚠️ Getting services into inline middleware

Inline middleware has no constructor, so there is nothing to inject into. You resolve from the request's own container:

app.Use(async (context, next) =>
{
    // RequestServices is the scoped container FOR THIS REQUEST
    var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
    var db     = context.RequestServices.GetRequiredService<AppDbContext>();

    logger.LogInformation("Handling {Path}", context.Request.Path);
    await next();
});

context.RequestServices is safe for scoped services, because it is the request scope. That is different from capturing a service in a closure, which would pin one instance for the life of the application — the captive dependency problem (6.4):

// ✗ WRONG — resolved once at startup, shared by every request forever
var db = app.Services.GetRequiredService<AppDbContext>();
app.Use(async (context, next) =>
{
    db.Orders.Add(...);        // one DbContext for the whole app. Not thread-safe.
    await next();
});

Resolving from RequestServices inside the lambda is the fix, and it is the one thing about inline middleware worth being careful with.

The deeper detail — modifying the response

Writing to the response after await next() usually fails:

app.Use(async (context, next) =>
{
    await next();

    context.Response.Headers["X-Duration"] = "42ms";
    // ✗ InvalidOperationException: "Headers are read-only, response has already started."
});

Once any bytes have been written, headers are on the wire and cannot change. The fix is OnStarting, which registers a callback that runs just before the first byte is sent:

app.Use(async (context, next) =>
{
    var start = Stopwatch.GetTimestamp();

    context.Response.OnStarting(() =>
    {
        var ms = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
        context.Response.Headers["X-Duration"] = $"{ms:F0}ms";
        return Task.CompletedTask;
    });

    await next();
});

Register the callback before calling next(), so it is in place before anything downstream starts writing. See 5.8.


Code

Genuinely good uses of inline middleware — each small, obvious, and unlikely to grow:

// 1. A correlation ID for tracing across services
app.Use(async (context, next) =>
{
    var correlationId = context.Request.Headers["X-Correlation-Id"].FirstOrDefault()
                        ?? Guid.NewGuid().ToString();

    context.Items["CorrelationId"] = correlationId;          // available downstream
    context.Response.Headers["X-Correlation-Id"] = correlationId;

    await next();
});
// 2. Security headers
app.Use(async (context, next) =>
{
    var headers = context.Response.Headers;
    headers["X-Content-Type-Options"] = "nosniff";
    headers["X-Frame-Options"] = "DENY";
    headers["Referrer-Policy"] = "no-referrer";

    await next();
});
// 3. Blocking a path outright — short-circuits, so next() is never called
app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/.git"))
    {
        context.Response.StatusCode = StatusCodes.Status404NotFound;
        return;                       // deliberately no next()
    }

    await next();
});

And one that should not be inline:

// ✗ Too much for a lambda — needs a class
app.Use(async (context, next) =>
{
    var apiKey = context.Request.Headers["X-Api-Key"].FirstOrDefault();
    if (string.IsNullOrEmpty(apiKey)) { /* ... */ }

    var repo = context.RequestServices.GetRequiredService<IApiKeyRepository>();
    var key = await repo.FindAsync(apiKey);
    if (key is null || key.IsRevoked || key.ExpiresAt < DateTimeOffset.UtcNow) { /* ... */ }

    // ...and twenty more lines of rate limiting and audit logging
});

That has dependencies, branching, and logic worth testing. It belongs in a class — 5.5.


Interview questions

Q: When would you write middleware inline rather than as a class?

When it is small, self-contained and unlikely to grow — adding a response header, setting a correlation ID, blocking a path. The benefit is that the logic sits in Program.cs where someone reading the pipeline will find it, without the ceremony of a class, a constructor and a registration extension method. I would move it to a class as soon as it needs dependencies beyond a quick RequestServices lookup, exceeds around ten lines, or is worth unit testing — and also to protect Program.cs, since its value is that the whole application's shape is visible at a glance.

Q: How does inline middleware get access to services?

Through context.RequestServices, which is the dependency injection scope for that specific request. That is important because it means scoped services like DbContext are resolved correctly, one per request. The mistake to avoid is resolving from app.Services outside the lambda and capturing the result in a closure — that gives you a single instance shared across every request for the life of the application, which for a DbContext is both a memory leak and a thread-safety bug.

Q: Why can't you set a response header after await next()?

Because by then the response has usually already started — headers are sent before the body, so once any bytes have been written they are on the wire and immutable. Attempting it throws an InvalidOperationException saying the headers are read-only. The fix is context.Response.OnStarting, which registers a callback that runs immediately before the first byte is sent, so you can still set headers based on work done during the request. The callback has to be registered before calling next, so it is in place before anything downstream writes.

Q: What is the difference between the two Use overloads?

The older one gives you next as a Func<Task> called with no arguments; the newer one, from .NET 7, gives you a RequestDelegate that you call with the context. The newer form avoids allocating a closure on every request, which matters in middleware that runs for every single request in a high-throughput service. You have to annotate the lambda parameter types explicitly, otherwise the compiler resolves to the older overload.


Traps ⚠️

  • Capturing a service resolved from app.Services pins one instance for the whole app. Use context.RequestServices inside the lambda.
  • Forgetting await next() ends the pipeline silently with an empty 200.
  • Setting headers after await next() throws. Use OnStarting, registered before next.
  • Program.cs filling with lambdas destroys the readability that makes it useful.
  • Inline middleware cannot be unit tested without spinning up the app.
  • The older Use overload allocates per request. Annotate types to get the newer one.
  • return without writing a response produces an empty 200, not a 404.


Sources