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