.net core 3.1在读取 Request.Body时不支持 Request.Body.Position = 0的设置

 ASP.NET Core 中的 Request.Body 虽然是一个 Stream ,但它是一个与众不同的 Stream —— 不允许 Request.Body.Position=0 ,这就意味着只能读取一次,要想多次读取,需要借助 MemoryStream 

在 .net core 3.0中修复了这个问题,只要启用倒带功能,就可以让  Request.Body 回归正常 Stream 。

需要引入程序集:Microsoft.AspNetCore.Http

使用方式:

在Startup.cs中定义Middleware,设置缓存Http请求的Body数据

app.Use(async (context, next) =>
{
        context.Request.EnableBuffering();
         await next.Invoke();
});

在使用出写:

        private string GetHttpBody()
        {
            Request.EnableBuffering();
            Request.Body.Position = 0;
            using (var reader = new StreamReader(Request.Body))
            {
                return reader.ReadToEnd();
            }
        }
原文地址:https://www.cnblogs.com/yxcn/p/14049349.html