Skip to content

Per-request log buffering throws ArgumentNullException at the end of a request #7806

Closed

Description

@evgenyfedorov2

Description

With per-request log buffering enabled (AddPerIncomingRequestBuffer), ILogger.Log throws ArgumentNullException when it's called after the request's services have been disposed but while IHttpContextAccessor.HttpContext still returns the request's HttpContext. This applies to every log record that passes the logging filters, including records that don't match any buffering rule, because PerRequestLogBufferManager.TryEnqueue reads HttpContext.RequestServices before the rules are evaluated.

ASP.NET Core writes its "Request finished" log record in that window. RequestServicesFeature registers the disposal of the request services with HttpResponse.RegisterForDisposeAsync, which adds an OnCompleted callback. Kestrel runs the OnCompleted callbacks and then calls HostingApplication.DisposeContext, which logs "Request finished" (through HostingApplicationDiagnostics.RequestEnd) before it clears IHttpContextAccessor. As a result, when Information level is enabled for Microsoft.AspNetCore.Hosting.Diagnostics, the exception is thrown on every request.

The client still receives the response. On the server, the exception propagates out of HostingApplication.DisposeContext, so the rest of the request teardown doesn't run:

  • Kestrel logs a warning, "Connection processing ended abnormally.", with the exception.
  • The "Request finished" log record isn't written.
  • http.server.request.duration isn't recorded, and http.server.active_requests isn't decremented.
  • The request Activity (Microsoft.AspNetCore.Hosting.HttpRequestIn) is never stopped.
  • IHttpContextAccessor.HttpContext isn't cleared: code started during the request still sees the request's HttpContext after the request has ended.

Without per-request buffering, the same app writes "Request finished", records both metrics, stops the Activity and clears IHttpContextAccessor.

Reproduction Steps

var builder = WebApplication.CreateBuilder(args);

// "Request finished" is logged at Information level in this category.
builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Information);
builder.Logging.AddPerIncomingRequestBuffer(LogLevel.Debug);

var app = builder.Build();
app.MapGet("/", () => "Hello");
app.Run();
  1. Create a project with dotnet new web and add the Microsoft.AspNetCore.Diagnostics.Middleware package.
  2. Replace the contents of Program.cs with the code above.
  3. Run the app and send it a request.

Expected behavior

ILogger.Log doesn't throw, and the request teardown completes. A log record written after the request's services have been disposed is handed to the global buffer, the same way as when IHttpContextAccessor.HttpContext is null.

Actual behavior

Each request returns HTTP 200 to the client, and Kestrel logs:

warn: Microsoft.AspNetCore.Server.Kestrel[0]
      Connection processing ended abnormally.
      System.ArgumentNullException: Value cannot be null. (Parameter 'provider')
         at System.ArgumentNullException.Throw(String paramName)
         at System.ArgumentNullException.ThrowIfNull(Object argument, String paramName)
         at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
         at Microsoft.AspNetCore.Diagnostics.Buffering.PerRequestLogBufferManager.TryEnqueue[TState](IBufferedLogger bufferedLogger, LogEntry`1& logEntry)
         at Microsoft.Extensions.Logging.ExtendedLogger.LegacyPath[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
         at Microsoft.Extensions.Logging.ExtendedLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
         at Microsoft.AspNetCore.Hosting.HostingApplicationDiagnostics.LogRequestFinished(Context context, Int64 startTimestamp, Int64 currentTimestamp)
         at Microsoft.AspNetCore.Hosting.HostingApplication.DisposeContext(Context context, Exception exception)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)

With TestServer, the exception also reaches the client: in my runs, HttpClient.GetAsync threw HttpRequestException ("Error while copying content to a stream.") with the ArgumentNullException as its innermost exception.

Regression?

No. PerRequestLogBufferManager has read HttpContext.RequestServices this way since per-request buffering was added in #5635, and the issue reproduces with the published 10.10.0 package.

Known Workarounds

Keep Information level disabled for Microsoft.AspNetCore.Hosting.Diagnostics, so that "Request finished" isn't logged. The appsettings.json files generated by the web, webapi, webapp, mvc, blazor and grpc templates do this by setting Microsoft.AspNetCore to Warning.

This doesn't help with other log records written in the same window. For example, ILogger.Log still throws when it's called from an HttpResponse.OnCompleted callback that was registered before the request services were first used: in my test, such a callback ran after the request services had been disposed.

Configuration

  • Microsoft.AspNetCore.Diagnostics.Middleware 10.10.0 from NuGet, on Kestrel
  • main at 0c15512, on TestServer
  • .NET 10.0.12 on macOS (arm64)

It reproduces with both Kestrel and TestServer. I haven't tested other operating systems.

Other information

PerRequestLogBufferManager.Flush and PerRequestLogBufferManager.TryEnqueue use HttpContext.RequestServices without checking it for null:

_httpContextAccessor.HttpContext?.RequestServices.GetService<IncomingRequestLogBufferHolder>()?.Flush();

IncomingRequestLogBufferHolder? bufferHolder =
httpContext.RequestServices.GetService<IncomingRequestLogBufferHolder>();

After RequestServicesFeature disposes the request services, its RequestServices getter returns null: DisposeAsync sets the backing field to null, and the getter only creates a scope if it hasn't created one before. Calling PerRequestLogBuffer.Flush() in that window throws the same exception.

Possible fixes:

  • In both methods, handle a null RequestServices the same way as a missing HttpContext.
  • ExtendedLogger calls LogBuffer.TryEnqueue outside the try/catch blocks it uses for logger and enricher calls, so an exception thrown by a log buffer propagates to the caller of ILogger.Log. Catching it there would keep a failing buffer from breaking the caller.

Found while working on #7781.

Activity

  1. added a commit that references this issue on Oct 7, 2026
  2. locked and limited conversation to collaborators on Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-telemetrybugThis issue describes a behavior which is not expected - a bug.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions