【问题标题】:Read the body of a request as string inside middleware将请求的正文作为中间件中的字符串读取
【发布时间】:2019-10-21 16:35:01
【问题描述】:

如何在 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);
    });
}

【问题讨论】:

    标签: c# asp.net-core asp.net-core-3.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.结果:

    参考:Write custom ASP.NET Core middleware

    【讨论】:

    • 这可行,但这样做会消耗流;在实践中,您可能希望将其提供给管道的其余部分。事实证明这是一个巨大的痛苦,因为 ASP.NET Core 3.0 中的 the relevant functionality is broken。 (谁会想到测试一个 Web 框架可以读取 Web 请求正文...)
    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 2020-11-27
    • 2017-09-20
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多