Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify response using middleware in ASP.NET Core 3

My goal is to write a middleware that will take care of logging requests to my API and API's responses to those requests in a DB. I already made a middleware that handles exceptions in a similar fashion, but I got stumped over this. When you read MSDN about Middleware you can see this nice picture:

ASP.NET Core 3

This makes you think that Middleware 2 receives the requests, does certain manipulations with it and passes it onto Middleware 3, then once all processing is done by middleware 3 it passes controls back to Middleware 2 for additional processing.

The only thing I do not understand is how to log the response if Middleware 2 Invoke() method is only called once during the request and not called during the response?

Startup.cs:

app.UseMiddleware<RequestLoggingMiddleware>();

Middleware:

 public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate nextMiddleware;

        public RequestLoggingMiddleware(RequestDelegate nextMiddleware)
        {
            this.nextMiddleware = nextMiddleware;
            this.options = options;
        }

        public async Task Invoke(HttpContext context)
        {
            System.Diagnostics.Debug.WriteLine("Middleware runs");
            await nextMiddleware(context);
        }
    }
}

In the example above I only see "Middleware runs" once in a console, during the initial request but before the response is made. How do I get it to run during the response cycle?

like image 839
AnKing Avatar asked Dec 18 '25 19:12

AnKing


1 Answers

To get the response, all you need to do is apply your same logic after the await nextMiddleware(context); line.

For example, to log the status code:

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate nextMiddleware;

    public RequestLoggingMiddleware(RequestDelegate nextMiddleware)
    {
        this.nextMiddleware = nextMiddleware;
    }

    public async Task Invoke(HttpContext context)
    {
        System.Diagnostics.Debug.WriteLine("Middleware runs");
        await nextMiddleware(context);
        System.Diagnostics.Debug.WriteLine($"Response Code: {context.Response.StatusCode}");
    }
}
like image 138
Matt Hensley Avatar answered Dec 20 '25 11:12

Matt Hensley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!