2

I created a simple endpoint filter on a C# minimal api and when I try to get the body into a string it is always blank.

app.MapPost("/todo", async (Todo todo) =>
{
    await Task.Run(() => { string x = "R";});
    return Results.Created($"/todo/{0}", 1);
})
.WithName("PostToDo")
.WithOpenApi()
.AddEndpointFilter(async (context, next) =>
{
    var body = context.HttpContext.Request.Body;

    using (var bodyReader = new StreamReader(body))
    {
        string rawBody = await bodyReader.ReadToEndAsync();
    }

    var result = await next(context);

    return result;
});
Guru Stron
  • 102,774
  • 10
  • 95
  • 132

1 Answers1

0

Body was read before hitting the filter. You need to enable buffering and then seek the stream before reading it:

app.Use((context, next) =>
{
    context.Request.EnableBuffering();
    return next();
});
app.MapPost("/todo", ...)
    .WithName("PostToDo")
    .WithOpenApi()
    .AddEndpointFilter(async (context, next) =>
    {
        var body = context.HttpContext.Request.Body;
        body.Seek(0, SeekOrigin.Begin);

        using (var bodyReader = new StreamReader(body))
        {
            string rawBody = await bodyReader.ReadToEndAsync();
        }

        var result = await next(context);

        return result;
    });
Guru Stron
  • 102,774
  • 10
  • 95
  • 132