1

How can I read the body value as string from HttpContext.Request in ASP.NET Core 3.0 middleware?

private static void MyMiddleware(IApplicationBuilder app)
{
    app.Run(async ctx =>
    {
        var body = ctx.Request.??????
        await context.Response.WriteAsync(body);
    });
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
user1613512
  • 3,590
  • 8
  • 28
  • 32

1 Answers1

2

Here are two ways to custom middleware like below:

1.The first way is that you could write middleware in Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       //...
        app.Run(async ctx =>
        {
            string body;
            using (var streamReader = new System.IO.StreamReader(ctx.Request.Body, System.Text.Encoding.UTF8))
            {
                body = await streamReader.ReadToEndAsync();
            }
            await ctx.Response.WriteAsync(body);
        });    
       //... 
    }

2.The second way is that you could custom middleware class like below:

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext httpContext)
    {
        string body;
        using (var streamReader = new System.IO.StreamReader(httpContext.Request.Body, System.Text.Encoding.UTF8))
        {
            body = await streamReader.ReadToEndAsync();
        }
        await httpContext.Response.WriteAsync(body);
    }
}

Then you need to register in Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //...
        app.UseMiddleware<MyMiddleware>();
        //...
    }

3.Result: enter image description here

Reference: Write custom ASP.NET Core middleware

Rena
  • 30,832
  • 6
  • 37
  • 72
  • 2
    This works but doing so consumes the stream; in practice, you'll probably want to make it available to the rest of the pipeline. And this turns out to be a huge pain, since [the relevant functionality is broken](https://stackoverflow.com/q/58737391/5085211) in ASP.NET Core 3.0. (Who'd have thought to test that a web framework could read web request bodies ...) – fuglede Feb 03 '20 at 19:30