Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Best way to log/read request body in a middleware ? #4962

Closed
IsaacSee opened this issue Jul 5, 2016 · 5 comments
Closed

Best way to log/read request body in a middleware ? #4962

IsaacSee opened this issue Jul 5, 2016 · 5 comments

Comments

@IsaacSee
Copy link

IsaacSee commented Jul 5, 2016

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.

@rynowak
Copy link
Member

rynowak commented Jul 5, 2016

@halter73 @CesarBS @Tratcher - do you think this is aspnet/KestrelHttpServer#940 ? What's the workaround for this?

@IsaacSee
Copy link
Author

IsaacSee commented Jul 5, 2016

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

@rynowak
Copy link
Member

rynowak commented Jul 5, 2016

Edit: oops, did not mean to close 😆

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?

@rynowak rynowak closed this as completed Jul 5, 2016
@rynowak rynowak reopened this Jul 5, 2016
@IsaacSee
Copy link
Author

IsaacSee commented Jul 5, 2016

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

@time-wcrp
Copy link

@IsaacSee Thank a lot.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants