Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 52 ยท Middleware and the Request Pipeline

Writing Custom Middleware

Write your own ASP.NET Core middleware: inline Use delegates, convention-based classes, IMiddleware, request timing and correlation id examples, and lifetimes.

The built-in middleware covers a lot, but every application eventually needs something of its own: stamp each response with the time it took, tag each request with an id that follows it through the logs, reject traffic from a blocked client, add a security header. Writing middleware is simple once you know the pattern, and there are three ways to write it, each suited to a different size of job.

In this lesson you will write inline middleware, a convention-based middleware class with its own extension method, and an IMiddleware class. Along the way you will build two real-world components, a request timer and a correlation id, and learn the lifetime rule that trips up most people. You should already know how the pipeline works from The Middleware Pipeline.

Choosing a style

Style Looks like Best for
Inline app.Use(async (context, next) => { ... }) A few lines, used once
Convention-based class a class with a constructor taking RequestDelegate next and a method InvokeAsync(HttpContext) Reusable, testable components (the usual choice)
IMiddleware a class implementing InvokeAsync(HttpContext, RequestDelegate), registered in DI When you want a new instance per request or full control by the container

All three produce exactly the same thing at run time: a function from RequestDelegate to RequestDelegate. The difference is how they are built and how long they live.

Inline middleware: a request timer

Start with the smallest form. This middleware measures how long the rest of the pipeline takes and reports it in a response header. Note the use of OnStarting: the header must be added before the response starts, and by the time await next() returns the body may already have been sent.

C# Inline timing middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The exact milliseconds differ on every run, so the demo prints only stable facts: the header is present, and only /slow reached 100 ms. This is a good habit in tests, too: assert on properties, not on measured times.

A convention-based middleware class

When middleware grows past a few lines, move it into a class. The framework uses a convention (no interface to implement):

  1. A public constructor whose first parameter is a RequestDelegate (the next component). Other parameters are injected from the container.
  2. A public method named Invoke or InvokeAsync, returning Task or ValueTask, whose first parameter is HttpContext. Further parameters are injected per request, so this is where scoped services go.

Register it with app.UseMiddleware<T>(), and wrap that call in an extension method so Program.cs reads nicely. Here is a correlation id component, which lets you follow one request through logs from many services.

sequenceDiagram
    participant C as Client
    participant M as CorrelationIdMiddleware
    participant E as Endpoint
    C->>M: GET /orders (X-Correlation-Id: abc or none)
    M->>M: reuse the header or generate a new id
    M->>M: store in context.Items and response header
    M->>E: next(context)
    E-->>M: response
    M-->>C: response with X-Correlation-Id

The middleware reads or creates the id before calling the rest of the pipeline and makes it available to everything inside.

C# A correlation id middleware class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three details deserve attention. First, the id is stored in context.Items, a dictionary that lives for exactly one request; later components (and your endpoints) read it from there. Second, a client-supplied value is untrusted input: the middleware ignores empty or over-long values rather than copying them into logs and headers. Third, the extension method hides UseMiddleware<T>(), which is the convention you will see across the framework (UseStaticFiles, UseCors, UseAuthentication).

Extra constructor parameters of a middleware class are resolved once from the container when the pipeline is built. You can also pass values directly: app.UseMiddleware<TimerMiddleware>(options) hands options to the constructor.

The lifetime rule

A convention-based middleware is created once, when the pipeline is built, and the same instance serves every request. That has a consequence: its constructor can only use singleton services. A scoped service (one whose lifetime is a single request) must be requested as an InvokeAsync parameter, because those are resolved per request.

IMiddleware offers the other model. The container creates the middleware instance through IMiddlewareFactory, and since you register the class in DI yourself, you choose its lifetime. A transient or scoped registration gives a new instance per request, so constructor injection of scoped services is safe.

C# Convention-based versus IMiddleware lifetimes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

After three requests the convention-based class was constructed once, while the transient IMiddleware was constructed three times. Both middleware saw the same RequestInfo per request as the endpoint did (request #1, #2, #3), which shows that a scoped service is shared within one request, whichever way it is injected.

If you inject a scoped service into the constructor of a convention-based middleware, the service is captured when the pipeline is built and then reused for every request, so it behaves like a singleton. With the default scope validation in development, ASP.NET Core throws an exception instead. Fix it by moving the parameter to InvokeAsync, or by switching to IMiddleware.

Practical rules for good middleware

  • Call next exactly once, unless you are deliberately short-circuiting. Calling it twice runs the rest of the pipeline twice.
  • Add response headers in OnStarting, not after next, because the response may already have started.
  • Never block: use await everywhere, and do not call .Result or .Wait() on tasks.
  • Keep it focused. One middleware, one job. Name it for the job (CorrelationId, RequestTiming).
  • Be careful reading the body. The request body is a forward-only stream. If you read it, you must enable buffering (context.Request.EnableBuffering()) and rewind it, otherwise the endpoint sees an empty body (HttpContext, Request and Response shows how).
  • Place it deliberately. A correlation id goes near the start so every later component and log line can use it; timing goes at the very start to include everything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a convention-based middleware class need?

    The convention is a constructor taking the next RequestDelegate and an Invoke/InvokeAsync method whose first parameter is HttpContext. No interface or attribute is required.
  2. 2. Where should a scoped service be requested in a convention-based middleware?

    The middleware instance is created once, so constructor services live as long as the app. Parameters of InvokeAsync are resolved per request, which suits scoped services.
  3. 3. How does the lifetime of an IMiddleware class differ from a convention-based class?

    IMiddleware is activated through IMiddlewareFactory from the service container, so its registered lifetime (transient, scoped) decides how often it is created.
  4. 4. Why does the timing middleware add its header inside Response.OnStarting?

    OnStarting callbacks run just before the first byte of the response is sent, the last moment when headers can still be changed.
  5. 5. A client sends a 500-character X-Correlation-Id. What should a careful middleware do?

    Headers come from the client and can be anything. Validating length or format and replacing bad values prevents log injection and header abuse.

Summary

  • Middleware can be written inline with app.Use, as a convention-based class used through UseMiddleware<T>, or as an IMiddleware class registered in DI.
  • A convention-based class has a RequestDelegate constructor and an Invoke/InvokeAsync(HttpContext, ...) method; wrap UseMiddleware<T> in an extension method.
  • Convention-based middleware is created once: constructor services must be singletons, and scoped services go on InvokeAsync parameters.
  • IMiddleware is created by the container, so its registered lifetime applies, including per-request instances.
  • Add headers with Response.OnStarting, store per-request data in HttpContext.Items, and treat incoming header values as untrusted.
  • Call next once, never block, and place each middleware deliberately in the pipeline.

Next: HttpContext, Request and Response