C#C
C#7mo ago
maca

Read body in FromBody and ActionFilter

hey guys, good evening, I'm new to C#

I'm trying to read the body of a request and if my endpoint has [FromBody] I can't read it through the HttpContext in the ActionFilter, if I remove it, works.
To tell you the truth I don't even know if I should use ActionFilter or a middleware, I don't really understand the difference...

endpoint
    [HttpPost("order")]
    [ValidateBlingWebhookAttribute]
    public Task Create([FromBody] OrderWebhookRequest<SalesOrderSummaryDTO> summary)
    {
        return Task.CompletedTask;
    }


filter
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {

        var request = context.HttpContext.Request;

        request.EnableBuffering();
        request.Body.Position = 0;

        using var reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true);
        var body = await reader.ReadToEndAsync();

        request.Body.Position = 0;
        await next();
    }


thanks in advance
Was this page helpful?