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 选项,使读取的内容能多次读取。默认读取一次就清理了。

posted @   过错  阅读(1557)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示