Daan
Daan

Reputation: 2928

How to log the response code of all web requests in .NET Core

In my .NET Core 2.2 Web Api project, I want to log any returned status code.

I created a standard Web Api project and modified a method to do exactly this.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Use(async (context, next) =>
    {
        Console.WriteLine($"RESPONSE STATUSCODE  + {context.Response.StatusCode}");
        await next.Invoke();
    });

    app.UseMvc();
}

I seems to work for regular calls. For example,

curl --silent -i http://localhost:5000/api/values | grep HTTP

returns

HTTP/1.1 200 OK

And the logging is:

RESPONSE STATUSCODE + 200

However, when I do this request

curl --silent -i http://localhost:5000/nonsense | grep HTTP

I get this returned:

HTTP/1.1 404 Not Found

And the logging is the same.....

RESPONSE STATUSCODE + 200

I just want to log my returned status code. That's all. How to do this? It seems to work fine if a 200 is returned but not in other situations.

Upvotes: 1

Views: 2814

Answers (1)

Alex Buyny
Alex Buyny

Reputation: 3185

This happens because your logging is placed incorrectly in the request pipeline, have a read about it here. When you log, the response is still a default one having 200 status code, the pipeline is not finished processing yet.

You'll need to move your logging to be the last in the pipeline for handling the response, and move the call after next.Invoke() like in this sample:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Use(async (context, next) =>
        {

            await next.Invoke();
            Console.WriteLine($"RESPONSE STATUSCODE  + {context.Response.StatusCode}");
        });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseMvc();


    }

Upvotes: 5

Related Questions