在中间件中以字符串形式读取请求的正文

时间:2019-10-19 17:03:28

标签: c# asp.net-core asp.net-core-3.0

如何在ASP.NET Core 3.0中间件中从HttpContext.Request中读取字符串形式的主体值?

private static void MyMiddleware(IApplicationBuilder app)
{
    app.Run(async ctx =>
    {
        var body = ctx.Request.??????
        await context.Response.WriteAsync(body);
    });
}

1 个答案:

答案 0 :(得分:1)

有两种自定义中间件的方法,如下所示:

1。第一种方法是您可以在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。第二种方法是您可以自定义如下的中间件类:

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

然后您需要在Startup.cs中注册:

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

3。结果: enter image description here

参考:Write custom ASP.NET Core middleware