How to auto log every request in .NET Core WebAPI?

ActionFilter will work until you need to log only requests processed by MVC middleware (as controller actions).

If you need logging for all incoming requests, then you need to use a middleware approach.

Good visual explanation:
enter image description here

Note that middleware order is important, and if your logging should be done at the start of pipeline execution, your middleware should be one of the first one.

Simple example from docs:

public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            // Do loging
            // Do work that doesn't write to the Response.
            await next.Invoke();
            // Do logging or other work that doesn't write to the Response.
        });

Leave a Comment