0Pricing
C# Academy · Lesson

Writing Custom Middleware

Create inline middleware with Use/Run/Map and class-based middleware with InvokeAsync for reusable components.

Why Custom Middleware?

Custom middleware handles cross-cutting concerns that apply to many requests: logging, timing, error handling, authentication, compression, caching. Writing it once means the logic runs automatically for every matching request.

Inline Middleware with Use

The quickest way to add middleware: pass a delegate to app.Use(). Good for prototyping or truly simple logic.

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

    await next(context);

    var elapsed = DateTimeOffset.UtcNow - start;
    context.Response.Headers.Append(
        "X-Elapsed", elapsed.TotalMilliseconds.ToString("F0") + "ms");
});

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