0

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:

enter image description here

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.

3
  • 1
    Check this Answer, You are most likely encountering this error System.InvalidOperationException: Headers are readonly, reponse has already started. Commented Feb 5, 2024 at 10:51
  • Yes that fixed the problem, thank you! Do you want to add your point as an answer and I'll accept it? Cheers Commented Feb 5, 2024 at 11:32
  • upvote the original answer that helped you, don't want to clutter SO especially since I'm not adding anything new to the original answer. Commented Feb 5, 2024 at 11:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.