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
- ASP.NET Core Pipeline Overview
- Writing Custom Middleware
- Short-Circuiting & Branching
- Middleware Ordering & Built-in Middleware