dotnet / dotnet/yarp

System.InvalidOperationException: Reading is already in progress.

Open
#2,655 7 comments 1 reaction 0 assignees View on GitHub
External: AspNetCore Type: Tracking
Dominant language
C#
Stars
9.6k
Forks
933
Avg merge
12d 18h
Merged PRs (30d)
2

Description

Hi, we have encountered below exception in our microservice serving as reverse proxy:

```
"MessageTemplate": "Connection id \"{ConnectionId}\", Request id \"{TraceIdentifier}\": An unhandled exception was thrown by the application.",
"RenderedMessage": "Connection id \"0HN7I0DFFRG93\", Request id \"0HN7I0DFFRG93:0000008C\": An unhandled exception was thrown by the application.",
"Exception": "Microsoft.AspNetCore.Connections.ConnectionAbortedException: The connection was aborted by the application.\n ---> System.InvalidOperationException: Reading is already in progress.\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.OnConsumeAsync()\n --- End of inner exception stack trace ---"
```

I have found several issues related to this topic:

- https://github.com/dotnet/aspnetcore/issues/33409
- https://github.com/microsoft/reverse-proxy/pull/1071
- https://github.com/dotnet/aspnetcore/issues/17840

The last one is suggesting that the reason may be invalid handling of reading request body. In our scenario there were no such operations (also buffering was not enabled). The only manipulation on body was as follows:

```c#
var originalBodyStream = context.Response.Body;
// Decorator counting bytes written to the stream
await using var monitoringStream = new Decorator(originalBodyStream);

try
{
context.Response.Body = monitoringStream;

await next(context);

await LogRequest();
}
catch (Exception)
{
// Error handling
}
finally
{
//Reassigning according to this advice: https://github.com/microsoft/reverse-proxy/issues/2385
context.Response.Body = originalBodyStream;
}
```

`LogRequest` is designed to log incoming request with optional logging of body. This option is however currently disabled. The only action taken is `context.Response.Body = originalBodyStream;`. What could be a cause of above exception and how could we prevent it?

We are currently using `Yarp.ReverseProxy` in `2.0.1` version (not updated because of https://github.com/microsoft/reverse-proxy/issues/2631).

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.