排名
1
文章
872
粉丝
112
评论
163
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

在以前framework版本中可以使用如下代码读取
StreamReader streamReader = new StreamReader(Request.InputStream);
string xml = streamReader.ReadToEnd();
在.net core中获取其实也类似
StreamReader streamReader = new StreamReader(Request.Body);
string content = streamReader.ReadToEnd();
但是这样会报错: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);
}
当然我们可能需要思考一下,为什么微软把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。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价