dotnet / dotnet/aspnetcore

Request Body disposed in EndRequest diagnostic event

Open
#9,258 4 comments 2 reactions 0 assignees View on GitHub
affected-very-few area-hosting area-networking enhancement severity-nice-to-have
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Describe the bug
The Request Body stream is disposed at some point before the `Microsoft.AspNetCore.Hosting.EndRequest` diagnostic event is fired. That means any diagnostic listener on the end request - including Application Insight's telemetry for requests - cannot read the body.

### To Reproduce
Steps to reproduce the behavior:
1. Using this version of ASP.NET Core '2.2.4'
2. Run this code

RequestDiagnosticListener:
```csharp
public class RequestDiagnosticListener
{
[DiagnosticName("Microsoft.AspNetCore.Hosting.BeginRequest")]
public virtual void OnRequestBeginning(HttpContext httpContext)
{
httpContext.Request.EnableBuffering();
if (httpContext.Request.Body.CanSeek)
{
var position = httpContext.Request.Body.Position;
}
}

[DiagnosticName("Microsoft.AspNetCore.Hosting.EndRequest")]
public virtual void OnRequestEnding(HttpContext httpContext)
{
if (httpContext.Request.Body.CanSeek)
{
var position = httpContext.Request.Body.Position;
}
}
}
```
Startup:
```csharp
public void Configure(DiagnosticListener diagnosticListener)
{
diagnosticListener.SubscribeWithAdapter(new RequestDiagnosticListener());
}
```
3. With any HTTP request to the application
4. Getting the position in `OnRequestBeginning` works as desired. See error `System.ObjectDisposedException: 'Cannot access a closed Stream.'` on `OnRequestEnding` access to the `Position` property.

### Expected behavior
Request Body should be able to be read in the `Microsoft.AspNetCore.Hosting.EndRequest` diagnostic event. If the Body is to be disposed, that should happen after the EndRequest event.

### Additional context
This is a continuation of an issue reported on Application Insights: https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/686

In .NET Framework, an Application Insights Telemetry Initializer for RequestTelemetry is able to read the content of the request. That functionality has been lost in AspNetCore.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.