ASP.NET Core Interview Question #81

How do you create custom middleware in ASP.NET Core?

Middleware & Request Pipeline Mid-Level Intermediate

Quick Interview Answer

Custom middleware is commonly implemented as a class with a constructor that receives RequestDelegate and an Invoke or InvokeAsync method that accepts HttpContext.

Detailed Explanation

Custom middleware is commonly implemented as a class with a constructor that receives RequestDelegate and an Invoke or InvokeAsync method that accepts HttpContext.

The middleware can also receive registered services through InvokeAsync parameters. After performing its pre-processing, it normally calls the next RequestDelegate unless it intentionally terminates the request.

An extension method is often added to make registration in Program.cs clear and reusable.

Code Example

public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestTimingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var started = Stopwatch.StartNew();

        await _next(context);

        started.Stop();
        Console.WriteLine($"Request took {started.ElapsedMilliseconds} ms");
    }
}

app.UseMiddleware<RequestTimingMiddleware>();