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

Buffering Request Body Stream #814

Closed
Badrinarayanan-Lakshmiraghavan opened this issue Jul 13, 2016 · 1 comment
Closed

Buffering Request Body Stream #814

Badrinarayanan-Lakshmiraghavan opened this issue Jul 13, 2016 · 1 comment

Comments

@Badrinarayanan-Lakshmiraghavan

First of all, I do not know where I should be asking his question. If this is not the right project, please let me know. I have a middleware like this that writes the request body out.

app.Use(next => async context =>
{
    var request = context.Request;
    var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    request.Body = buffer;
    string body = System.Text.Encoding.UTF8.GetString(buffer.ToArray());
    buffer.Position = 0;

    await next.Invoke(context);
});

This works correctly for the first request. For the subsequent request, request.Body continues to be a MemoryStream and the request body of the second message is not being copied into buffer, since request.body is not the network stream.

If I change the code like this, it works.

app.Use(next => async context =>
{
    var request = context.Request;
    var buffer = new MemoryStream();
    var originalStream = request.Body;
    await request.Body.CopyToAsync(buffer);
    request.Body = buffer;
    string body = System.Text.Encoding.UTF8.GetString(buffer.ToArray());
    buffer.Position = 0;

    await next.Invoke(context);

    request.Body = originalStream;
});

But why do I need to restore the request body stream so that it works correctly for the next request? It seems very weird, at least to me.

@Tratcher
Copy link
Member

This is a bug in kestrel: aspnet/KestrelHttpServer#940

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

2 participants