I have implemented a middleware class that determines the elapsed time that a page took to load.
public sealed class PageLoadTimeMiddleware
{
private readonly RequestDelegate _next;
public PageLoadTimeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
context.Items["Stopwatch"] = stopwatch;
await _next(context);
stopwatch.Stop();
var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
context.Response.Headers.Add("X-PageLoadTime", elapsedMilliseconds.ToString());
}
}
In my Program.cs file, I configure the middleware to run:
app.UseMiddleware<PageLoadTimeMiddleware>();
However, when I run the web application, it gives me the following error page:
If I disable the middleware, the web application runs perfectly.
How can I debug this?
Can you provide any insight into why this might be happening?
FWIW, I am calling lots of different things in my Program.cs file (both before and after this middleware is configured).
Thanks
UPDATE: I've extracted this code out into a fresh "out of the box" C# ASP.Net MVC Core web application, and the result is still the same. The application just hangs when I try to run it.

System.InvalidOperationException: Headers are readonly, reponse has already started.