Mvc: Best way to log/read request body in a middleware ?

Created on 5 Jul 2016  路  5Comments  路  Source: aspnet/Mvc

Hello,

For logging concern we need to read and rewind the request body.
With pre-rc2 we used EnableRewind() to read then rewind the body stream.

But with 1.0.0, it seems that Kestrel uses stream pooling, resulting in ObjectDisposed Exceptions on the following request after calling EnableRewind().

Is there a new way to read the body before MVC [FromBody] ?
Or is this an issue ?

Thanks.

Most helpful comment

Yes, thanks again !

Here is the resulting snippet, including the workaround.

var initialBody = context.Request.Body; // Workaround

request.EnableRewind();
using (var reader = CreateLeaveOpenStreamReader(context.Request.Body))
{
    var body = await reader.ReadToEndAsync();
    context.Request.Body.Position = 0;
    // Do something with body
}

await next(context);

context.Request.Body = initialBody; // Workaround

All 5 comments

@halter73 @cesarbs @Tratcher - do you think this is https://github.com/aspnet/KestrelHttpServer/issues/940 ? What's the workaround for this?

Thanks @rynowak.
I did not found the referenced issue on Kestrel, I can confirm this is the same issue.

Edit: oops, did not mean to close :laughing:

It seems like you might be able to work around the problem like so:

var body = context.Request.Body;
try
{
    context.EnableRewind();
    await next(context);
}
finally
{
    context.Request.Body = body;
}

Does that work?

Yes, thanks again !

Here is the resulting snippet, including the workaround.

var initialBody = context.Request.Body; // Workaround

request.EnableRewind();
using (var reader = CreateLeaveOpenStreamReader(context.Request.Body))
{
    var body = await reader.ReadToEndAsync();
    context.Request.Body.Position = 0;
    // Do something with body
}

await next(context);

context.Request.Body = initialBody; // Workaround

@IsaacSee Thank a lot.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

workmonitored picture workmonitored  路  3Comments

LiangZugeng picture LiangZugeng  路  3Comments

karthicksundararajan picture karthicksundararajan  路  4Comments

CezaryRynkowski picture CezaryRynkowski  路  4Comments

KLuuKer picture KLuuKer  路  3Comments