0

Why does this code only gets executed when no error has occurred?

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();
});

Is there an easy way to log the url and optionally body of the request when an unhandled exception occurs?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Noah Bergh
  • 493
  • 4
  • 14

1 Answers1

1

I suggest you take a look at this to get to know how to extract the request body, and then for when exception happen, use something like

// 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
                }
            });
Gordon Khanh Ng.
  • 1,352
  • 5
  • 12