How do you write a custom middleware?
Create a class with:
- A constructor accepting RequestDelegate
- An Invoke or InvokeAsync method
public class MyCustomMiddleware
private readonly RequestDelegate _next;
public MyCustomMiddleware(RequestDelegate next) => _next =
next;
public async Task InvokeAsync(HttpContext context)
// Pre-processing logic
await _next(context);
// Post-processing logic
Register it:
app.UseMiddleware<MyCustomMiddleware>();