15

I am having a simple middleware which fetches the body of the request and store it in a string. It is reading fine the stream, but the issue is it wont call my controller which called just after I read the stream and throw the error

A non-empty request body is required

. Below is my code.

  public async Task Invoke(HttpContext httpContext)
            {
                var timer = Stopwatch.StartNew();
                ReadBodyFromHttpContext(httpContext);
                await _next(httpContext);
                timer.Stop();
            }

   private string ReadBodyFromHttpContext(HttpContext httpContext)
        {
           return await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
        }
1

5 Answers 5

19

You need to convert HttpContext.Request.Body from a forward only memory stream to a seekable stream, shown below.

//  Enable seeking
context.Request.EnableBuffering();
//  Read the stream as text
var bodyAsText = await new System.IO.StreamReader(context.Request.Body).ReadToEndAsync();
//  Set the position of the stream to 0 to enable rereading
context.Request.Body.Position = 0; 
7
  • 2
    FYI in .NetCore 3.1 Request.Body.Position throws NotSupportedException
    – w00ngy
    Commented Jan 9, 2020 at 18:42
  • @w00ngy I've just tested in net core 3.1 and it work as expected: context.Request.Body.Position = 0; throws no exception Commented Jan 15, 2020 at 12:05
  • 2
    maybe I didn't have EnableBuffering set or something. Disregard.
    – w00ngy
    Commented Jan 16, 2020 at 2:18
  • 1
    The returned string is always "". I can see request.ContentLength is 722. But whether I try the above code or try to use a memory stream to retrieve a byte array, it always returns empty. Any ideas why this might be happening?
    – Ash
    Commented Jan 17, 2023 at 6:26
  • 1
    @mattinsalto for a complete example I guess you need to properly dispose the StreamReader but also configure it to not dispose the underlying stream. See this answer: stackoverflow.com/a/57285744/129269
    – riezebosch
    Commented Nov 2, 2023 at 11:09
10

when it comes to capturing the body of an HTTP request and/or response, this is no trivial effort. In ASP .NET Core, the body is a stream – once you consume it (for logging, in this case), it’s gone, rendering the rest of the pipeline useless.

Ref:http://www.palador.com/2017/05/24/logging-the-body-of-http-request-and-response-in-asp-net-core/

public async Task Invoke(HttpContext httpContext)
    {
        var timer = Stopwatch.StartNew();
        string bodyAsText = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
        var injectedRequestStream = new MemoryStream();
        var bytesToWrite = Encoding.UTF8.GetBytes(bodyAsText);
        injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
        injectedRequestStream.Seek(0, SeekOrigin.Begin);
        httpContext.Request.Body = injectedRequestStream;
        await _next(httpContext);

        timer.Stop();
    }
1
  • 1
    Basically what I was suggesting in the comments. yep.
    – Nkosi
    Commented Dec 4, 2017 at 1:24
7

Few things are crucial here:

  • enable buffering
  • last flag leaveOpen in StreamReader
  • reset request body stream position (SeekOrigin.Begin)
public void UseMyMiddleware(IApplicationBuilder app)
{
    app.Use(async (context, next) =>
    {
        context.Request.EnableBuffering();

        using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, false, 1024, true))
        {
            var body = await reader.ReadToEndAsync();

            context.Request.Body.Seek(0, SeekOrigin.Begin);
        }

        await next.Invoke();
    });
}
1
  • Nice you show the full example of disposing the reader but leaving the stream open 👍🏻
    – riezebosch
    Commented Nov 2, 2023 at 11:16
1
using (var mem = new MemoryStream())
            using (var reader = new StreamReader(mem))
            {
                Request.Body.CopyTo(mem);
                var body = reader.ReadToEnd();

//and this you can reset the position of the stream.

                mem.Seek(0, SeekOrigin.Begin);
                body = reader.ReadToEnd();
            }

Here you are can read how it works. https://gunnarpeipman.com/aspnet-core-request-body/

0

You can try this

public async Task Invoke(HttpContext context)
{
  var request = context.Request;
  request.EnableBuffering();
  var buffer = new byte[Convert.ToInt32(request.ContentLength)];
  await request.Body.ReadAsync(buffer, 0, buffer.Length);
  var requestContent = Encoding.UTF8.GetString(buffer);
  request.Body.Position = 0;  //rewinding the stream to 0
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.