ASP.NET Core 中不能多次读取 Request.Body和设置Position的问题

Asp.Net Core与以往Asp.Net在对待HttpContext.Request的Steam(在.Net Core中是属性Body,.Net中对应的属性是InputStream)的处理机制有点不同,Asp.Net Core的Request.Body默认情况下不允许 Request.Body.Position=0 ,这就意味着只能读取一次,要想多次读取,在 ASP.NET Core 2.1 中提供的解决方法是在第一次读取前通过Request.EnableRewind() 【需要引用命名空间 Microsoft.AspNetCore.Http.Internal】,启用倒带功能,就可以让  Request.Body 回归正常 Stream 。在NET Core 3.1 中调用的方法是 Request.EnableBuffering 【发现Core 2.1中也有提供EnableBuffering方法,需要引入Microsoft.AspNetCore.Http命名空间】

EnableRewind 有 2 个参数 bufferThreshold 与 bufferLimit 。 bufferThreshold 设置的是 Request.Body 最大缓存字节数(默认是30K),超出这个阈值的字节会被写入磁盘;bufferLimit 设置的是 Request.Body 允许的最大字节数(默认值是null),超出这个限制,就会抛出异常  System.IO.IOException 。

EnableRewind 的实现源代码见 BufferingHelper.cs

以下是项目代码实例【Action方法过滤器(SignaturerFilterAttribute : Attribute, IActionFilter)验证签名时的应用场景】:

        private bool Verify(ActionExecutingContext context)
        {            
            var request = context.HttpContext.Request;           
            request.EnableRewind();
            request.Body.Seek(0, SeekOrigin.Begin);            
            var sr = new StreamReader(request.Body);
            string json = sr.ReadToEnd();
            request.Body.Seek(0, SeekOrigin.Begin);
            ..................
        }

 

参考:

https://www.cnblogs.com/dudu/p/9190747.html

https://stackoverflow.com/questions/40494913/how-to-read-request-body-in-a-asp-net-core-webapi-controller          

你可能感兴趣的:(.Net)