.net core mv5 通过Request.Body原始流获取http请求体json数据

1 修改 Startup.cs 中的 Configure方法添加如下中间件 允许多次读取请求体

            // 允许多次读取 HttpContext.Body 请求体流数据
            app.Use(next => new RequestDelegate(
                async context =>
                {
                    context.Request.EnableBuffering();
                    await next(context);
                })
            );

2 读取参考代码如下:

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.HttpContext.Request.Method.ToUpper() == "POST")
            {
                var stream = context.HttpContext.Request.Body;
                if (stream != null)
                {
                    string bodyStr = null;
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        bodyStr = await reader.ReadToEndAsync();
                        stream.Seek(0, SeekOrigin.Begin);
                    }
                    if (!bodyStr.IsEmpty())
                    {
                        if (VerifySign(JObject.Parse(bodyStr)))
                        {
                            // 验签成功才继续执行
                            await next();
                            return; // 执行完管道其他操作后立即返回
                        }
                    }
                }
            }

            // 设置短路,返回响应
            await HandleAsync(context.HttpContext, ResultModel.Create(ResutlCodeEnum.验签失败));
            return;
        }

 

注意:目前参考代码仅适用于 Post请求,Content-Type 为 application/json

 

参考链接

https://www.cnblogs.com/kklldog/p/core-mvc-modelbind.html

posted @ 2021-01-04 21:10  温故纳新  阅读(1167)  评论(0编辑  收藏  举报