Mike Zhang
Mike Zhang

Reputation: 3

How to get the correct response body in netcore middleware?

I'm writing a middleware to write api request log.

But sometimes the Response Log will be written twice. Here is a code sample :

public class TestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    private int After = 0;
    private int Before = 0;

    public TestLoggingMiddleware(RequestDelegate next, ILoggerFactory logfac)
    {
        _logger = logfac.CreateLogger("ApiRequest");
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        Before = 0;
        After = 0;

        Before++;
        await _next(context);
        After++;
        After++;
        if (After > 2)
        {
            _logger.LogError($"{context.Request.Path.ToString()}_{Before}_{After}");
        }
    }


}

Before=1 And After=4. This problem only comes up occasionally.

netcore Version is 3.1 . The Code Run in the docker.

Anybody knows what the problem is?

Upvotes: 0

Views: 95

Answers (1)

Paulo Morgado
Paulo Morgado

Reputation: 14836

You're running this code for every request and maintaining a global state.

This might work fine for a single request, but it fails as soon as there is more than one request at the same time.

Upvotes: 1

Related Questions