1

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.

1 Answer 1

5

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();


    }
Sign up to request clarification or add additional context in comments.

Comments

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.