how to read post body in request filter?

mc 1,921 Reputation points
2023-05-19T06:19:10.14+00:00
builder.Services.AddControllers(options =>
{
    options.Filters.Add<RequestFilter>();
});

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?

ASP.NET Core
ASP.NET Core
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
    2023-05-24T02:23:11.95+00:00

    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,

    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful