user1613512
user1613512

Reputation: 3640

Read the body of a request as string inside middleware

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

Upvotes: 1

Views: 3508

Answers (1)

Rena
Rena

Reputation: 36565

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

Upvotes: 2

Related Questions