未分类
#Web #.NET5 #WebApi #接收httpPost #文本流数据

.NET5 webApi项目接收HttpPost文本流数据

Y Yuan天空
2021-06-15 120 阅读

正文详情 · 630 字

.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<IISServerOptions>(options =>
{
         options.AllowSynchronousIO = true;
});

内容创作不易,转载请务必注明本文来源链接,感谢您的尊重与支持~

没有更多了~
这是最早的一篇了
相关推荐