c# - 缓冲流 - ASP.NET Core 3.0 中不允许同步操作
问题描述
我有一个针对 AspNetCore 2.2 的 REST API,其端点允许下载一些大的 json 文件。迁移到 AspNetCore 3.1 后,此代码停止工作:
try
{
HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
HttpContext.Response.Headers.Add("Content-Type", "application/json");
using (var bufferedOutput = new BufferedStream(HttpContext.Response.Body, bufferSize: 4 * 1024 * 1024))
{
await _downloadService.Download(_applicationId, bufferedOutput);
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
这是下载方法,它创建了我想在 HttpContext.Response.Body 上返回的 json:
public async Task Download(string applicationId, Stream output, CancellationToken cancellationToken = default(CancellationToken))
{
using (var textWriter = new StreamWriter(output, Constants.Utf8))
{
using (var jsonWriter = new JsonTextWriter(textWriter))
{
jsonWriter.Formatting = Formatting.None;
await jsonWriter.WriteStartArrayAsync(cancellationToken);
//write json...
await jsonWriter.WritePropertyNameAsync("Status", cancellationToken);
await jsonWriter.WriteValueAsync(someStatus, cancellationToken);
await jsonWriter.WriteEndArrayAsync(cancellationToken);
}
}
}
现在我得到这个异常:“在 ASP.NET Core 3.0 中不允许同步操作”如何在不使用 AllowSynchronousIO = true 的情况下更改此代码以工作;
解决方案
AllowSynchronousIO
.Net core 3.0.0-preview3
默认情况下,从( Kestrel
, HttpSys
, IIS in-process
, ) 中禁用该选项,TestServer
因为这些 API 是线程饥饿和应用程序挂起的根源。
可以根据临时迁移的每个请求覆盖该选项:
var allowSynchronousIoOption = HttpContext.Features.Get<IHttpBodyControlFeature>();
if (allowSynchronousIoOption != null)
{
allowSynchronousIoOption.AllowSynchronousIO = true;
}
您可以找到更多信息并关注 ASP.NET Core 问题跟踪器:AllowSynchronousIO disabled in all servers
推荐阅读
- c++ - 返回流运算符的代理类时解包参数
- mutex - 受精中受精卵的形成是互斥体的一个例子吗?
- oracle - APEX 与 SQL Developer 中的查询结果不同
- react-native - 如何在结合使用 createStackNavigator 和 create createDrawerNavigator 时设置默认屏幕
- php-7 - 我的 sql 关闭语句有错误,无法找到解决方法
- python - 使用已由另一个函数生成的密钥和 vigenere 密码加密字符串
- r - 根据列表过滤数据框 - 但是包含
- jpa - JPQL 中的命名参数
- css - CSS 是个问题。元素本身赋值
- c++ - 自 C++17 的类模板参数推导以来,std::make_move_iterator 是多余的吗?