.net core 读取Request.Body内容,读取request输入流的内容 电脑版发表于:2021/5/19 17:58 #### 在以前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(); ```