.NET5 webApi项目接收HttpPost文本流数据
NET Framework 中web项目接收Post数据可以通过Request.InputStream 来取得,但在.NET 5中貌似行不通了。 以下是在.NET5中读取post内容的方法
//获取PostBody的文本流内容 string GetPostBody(HttpRequest Request) { using (var buffer = new MemoryStream()) { this.Request.Body.CopyTo(buffer); buffer.Position = 0;//一定要加上 var reader = new StreamReader(buffer, System.Text.UTF8Encoding.Default); return reader.ReadToEndAsync().Result; } }
如果运行出现以下错误:
Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead
解决办法:
在 public void ConfigureServices(IServiceCollection services) 方法内添加以下代码即可
services.Configure(options => { options.AllowSynchronousIO = true; });