Search code examples
c#asp.net-coreerror-logging

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


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?


Solution

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