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?

1 Answer 1

7

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}");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

How do you add a response header based on the request logic? I tried your code but "context.Response.Headers.Add("X-Test", "test");" does not work.

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.