Repository navigation
Description
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.durationisn't recorded, andhttp.server.active_requestsisn't decremented.- The request
Activity(Microsoft.AspNetCore.Hosting.HttpRequestIn) is never stopped. IHttpContextAccessor.HttpContextisn't cleared: code started during the request still sees the request'sHttpContextafter 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();- Create a project with
dotnet new weband add theMicrosoft.AspNetCore.Diagnostics.Middlewarepackage. - Replace the contents of
Program.cswith the code above. - 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.Middleware10.10.0 from NuGet, on Kestrelmainat 0c15512, onTestServer- .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:
Line 32 in 0c15512
| _httpContextAccessor.HttpContext?.RequestServices.GetService<IncomingRequestLogBufferHolder>()?.Flush(); |
Lines 45 to 46 in 0c15512
| 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
nullRequestServicesthe same way as a missingHttpContext. ExtendedLoggercallsLogBuffer.TryEnqueueoutside thetry/catchblocks it uses for logger and enricher calls, so an exception thrown by a log buffer propagates to the caller ofILogger.Log. Catching it there would keep a failing buffer from breaking the caller.
Found while working on #7781.
Activity
Remove the #7806 workaround from the per-request scopes test