Using middleware for logging or performance (e.g. measuring?
execution time)
Example custom middleware to measure time:
public class TimingMiddleware
private readonly RequestDelegate _next;
public TimingMiddleware(RequestDelegate next) => _next =
next;
public async Task InvokeAsync(HttpContext context)
var sw = Stopwatch.StartNew();
await _next(context);
sw.Stop();
Console.WriteLine($"Request took
{sw.ElapsedMilliseconds} ms");
Register:
app.UseMiddleware<TimingMiddleware>();
Dependency Injection (DI)