Search code examples
c#.net-7.0minimal-apis

Getting the request body as a string in and EndpointFilter .Net 7


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;
});

Solution

  • 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;
        });