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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With