TNBLOG
首页
博客
视频
资源
问答
猿趣
手机
关于
搜索
收藏
便签
笔记
消息
创作
登录
剑轩
故如虹,知恩;故如月,知明
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
CSS
15篇
微服务
41篇
Git
14篇
.NET
102篇
移动开发
33篇
软件架构
23篇
.NET Core
119篇
.NET MVC
11篇
英语
3篇
随笔
86篇
Bootstrap
3篇
Redis
21篇
编辑器
10篇
Js相关
15篇
虚拟化
8篇
更多
Oracle
7篇
Python
14篇
数据库
26篇
EF
17篇
微信
3篇
前端
151篇
消息队列
6篇
docker
41篇
多线程
1篇
Java
4篇
软件基础
2篇
C++
2篇
WCF
7篇
Linux
7篇
nginx
5篇
K8S
9篇
ABP
2篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术
原
.net core 读取Request.Body内容,读取request输入流的内容
5036
人阅读
2021/5/19 17:58
总访问:
3977666
评论:
0
收藏:
0
手机
分类:
.NET Core
#### 在以前framework版本中可以使用如下代码读取 ``` StreamReader streamReader = new StreamReader(Request.InputStream); string xml = streamReader.ReadToEnd(); ``` #### 在.net core中获取其实也类似 ``` StreamReader streamReader = new StreamReader(Request.Body); string content = streamReader.ReadToEnd(); ``` tn6>但是这样会报错:Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead. 大概意思就是说不能同步获取,要么使用异步获取要么配置一下允许同步获取,微软默认的配置是不允许同步读取这个流的 #### 使用同步的方式来读取 设置一下即可: ``` services.Configure<KestrelServerOptions>(options => { options.AllowSynchronousIO = true; }); ``` 或者这样: ``` public override void OnActionExecuting(ActionExecutingContext context) { var syncIOFeature = context.HttpContext.Features.Get<IHttpBodyControlFeature>(); if (syncIOFeature != null) { syncIOFeature.AllowSynchronousIO = true; } StreamReader stream = new StreamReader(context.HttpContext.Request.Body); string body = stream.ReadToEnd(); base.OnActionExecuting(context); } ``` tn2>当然我们可能需要思考一下,为什么微软把AllowSynchronousIO默认设置为false,说明微软并不希望我们去同步读取Body。 Kestrel默认情况下禁用 AllowSynchronousIO(同步IO),线程不足会导致应用崩溃,而同步I/O API(例如HttpRequest.Body.Read)是导致线程不足的常见原因。所以还是推荐使用异步的方式来读取。 #### 异步方式来读取 使用如下代码来读取即可,不需要配置也很简单! ``` StreamReader streamReader = new StreamReader(Request.Body); string content = streamReader.ReadToEndAsync().GetAwaiter().GetResult(); ```
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}