how to read post body in request filter?

mc 1,921 Reputation points
builder.Services.AddControllers(options =>

I want to read the post/get/put body

the api is public async Task<JsonResult> Login([FromBody] Dtos.UserLoginDto user)

if (context.Request.Body.CanSeek) { context.Request.Body.Seek(0, SeekOrigin.Begin); } using (var stream = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, leaveOpen: true)) { para = await stream.ReadToEndAsync(); }

it is an empty string why?

A set of technologies in the .NET Framework for building web applications and XML web services.
3,142 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 24,236 Reputation points Microsoft Vendor

    Hi @mc

    From we previous discuss, the issue relates the RequestFilter. You can try to remove it.

    Then, to read the request body in the action method, we should not use the [FromBody] attribute and parameters. Because the request body can only be read once, from beginning to end. So, after model binding, if we still using the StreamReader to reader the request body, it will return empty.

    So, you can refer to the following code to read the request body in the action method:

    User's image

    More detail information about the HttpContext, see Use HttpContext in ASP.NET Core (#Enable request body buffering).

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,


    0 comments No comments

0 additional answers

Sort by: Most helpful