Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'MemoryPool'. .NET6

Getting following error

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'MemoryPool'. while reading requestBody from middleware.

Reading request body as follows

using (StreamReader reader = new StreamReader(context.Request.Body))
{
    context.Request.Body.Position = 0;
    requestBody = await reader.ReadToEndAsync();
    context.Request.Body.Position = 0;
}

Error comes completely randomly

like image 773
tushar bansal Avatar asked Sep 01 '25 01:09

tushar bansal


1 Answers

Pass leaveOpen parameter to the StreamReader:

using (StreamReader reader = new StreamReader(context.Request.Body, leaveOpen: true))
{
    context.Request.Body.Position = 0;
    requestBody = await reader.ReadToEndAsync();
    context.Request.Body.Position = 0;
}

Also note that perfromance-wise reading request multiple times can have detrimental effect. And check out build-in HttpLoggingMiddleware for some inspirations which also reads the request body.

like image 85
Guru Stron Avatar answered Sep 02 '25 15:09

Guru Stron