net core 3.0 读取post请求body方法


读取报错了

一 错误信息:Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronou

二 解决方法

1 在startup中设置同步读取方式,读取body内容。默认是异步

  services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
     .Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);

2

string body=string.Empty;
 int bufferThreshold = 5120000;//500k  bufferThreshold 设置的是 Request.Body 最大缓存字节数(默认是30K) 超出这个阈值的字节会被写入磁盘
                int bufferLimit = 10240000;//1m 设置的是 Request.Body 允许的最大字节数(默认值是null),超出这个限制,就会抛出异常 System.IO.IOException
                Request.EnableBuffering(bufferThreshold, bufferLimit);
                HttpContext.Request.Body.Position = 0;
                if (this.Request.ContentLength > 0 && this.Request.Body != null && this.Request.Body.CanRead)
                {
                    Encoding encoding = System.Text.UTF8Encoding.Default;
                    using (var buffer = new MemoryStream())
                    {
                        HttpContext.Request.Body.CopyTo(buffer);
                        buffer.Flush();
                        buffer.Position = 0;
                        body = buffer.GetReader().ReadToEnd();
                    }
                }

body即为读取到的内容。
如果是文件的话 保存方法为 buffer.ToFile(文件路径);
Request.EnableBuffering 选项,使读取的内容能多次读取。默认读取一次就清理了。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM