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

MicahZoltu picture MicahZoltu  路  37Comments

dougbu picture dougbu  路  125Comments

johnnyoshika picture johnnyoshika  路  57Comments

skyflyer picture skyflyer  路  40Comments

grahamehorner picture grahamehorner  路  52Comments