asp net core 出错时如何记录请求url?

How to log the request url when an error occurs in asp net core?

为什么只有在没有错误发生时才执行这段代码?

app.Use(async (context, next) => {
    Console.WriteLine(context.RequestAborted.IsCancellationRequested);

    if(context.Response.StatusCode < 200 || context.Response.StatusCode > 299) {
        Console.WriteLine();
        Console.WriteLine(context.Request.Method);
        Console.WriteLine(context.Request.Path);
    }
    
    await next.Invoke();
});

有没有一种简单的方法可以在发生未处理的异常时记录 url 和可选的请求正文?

我建议你看一下this来了解如何提取请求体,然后当异常发生时,使用类似

的东西
// remember to put this as high in the pipeline as you need
app.Use(async (context, next) => {
                try
                {
                    await next.Invoke();
                }
                catch (Exception e)
                {
                    // Extract Http request body, logging out the exception,... everything that you see necessary
                }
            });