ASP.NET Core 3.1 reading Request body empty string

Viewed 531

So I have this:

app.Use(async (context, next) =>
            {
                context.Request.EnableBuffering();
                await next();
            });

And this:

private async Task<JObject> GetRequestBodyAsync(HttpRequest request)
{
        JObject objRequestBody = new JObject();

        try
        {
            // IMPORTANT: Leave the body open so the next middleware can read it.
            using (StreamReader reader = new StreamReader(
                request.Body,
                Encoding.UTF8,
                detectEncodingFromByteOrderMarks: false,
                leaveOpen: true))
            {
                string strRequestBody = await reader.ReadToEndAsync();
                objRequestBody = JsonConvert.DeserializeObject<JObject>(strRequestBody);
            }
        }
        finally
        {
            // IMPORTANT: Reset the request body stream position so the next middleware can read it
            request.Body.Position = 0;
        }

        return objRequestBody;
}

But although request.Body.Length > 0 (as expected), this line:

string strRequestBody = await reader.ReadToEndAsync();

always returns an empty string. Any ideas?

The next action that follows retrieves [FromBody] OK.

1 Answers

I got the same problem in an application after an upgrade from .NET Core 2.2 to 3.1 and found the solution.

In the startup.cs your code must be at the begining of the pipeline : `

public void Configure(IApplicationBuilder app)
{
    app.Use((context, next) =>
    {
        context.Request.EnableBuffering();
        return next();
    });


    // ...More configurations go here
}

After that you can use this in your code :

    private async Task<JObject> GetRequestBodyAsync(HttpRequest request)
    {
        JObject objRequestBody = new JObject();

        try
        {
            // set the pointer to the beninig of the stream in case it already been readed
            request.Body.Position = 0; 
            using (StreamReader reader = new StreamReader(request.Body)
            {
                string strRequestBody = await reader.ReadToEndAsync();
                objRequestBody = JsonConvert.DeserializeObject<JObject>(strRequestBody);
            }
        }
        finally
        {
            request.Body.Position = 0;
        }

        return objRequestBody;
}

For more informations : https://justsimplycode.com/2020/08/02/reading-httpcontext-request-body-content-returning-empty-after-upgrading-to-net-core-3-from-2-0/

Related