缓冲流 - ASP.NET Core 3.0 中不允许同步操作 [英] Buffered Stream - Synchronous operations are disallowed in ASP.NET Core 3.0
问题描述
我有一个针对 AspNetCore 2.2 的 REST API,其端点允许下载一些大的 json 文件.迁移到 AspNetCore 3.1 后,此代码停止工作:
I had an REST API targeting AspNetCore 2.2 with an endpoint that allows download of some big json files. After migrating to AspNetCore 3.1 this code stopped working:
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:
This is the download method, that created the json that I want to return on the HttpContext.Response.Body:
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 的情况下更改此代码以使其正常工作;
Now I get this exception: "Synchronous operations are disallowed in ASP.NET Core 3.0" How can I change this code to work without using AllowSynchronousIO = true;
推荐答案
AllowSynchronousIO
选项在 .Net core 3.0.0-preview3
中默认禁用 (>Kestrel
、HttpSys
、IIS 进程内
、TestServer
),因为这些 API 是线程饥饿和应用程序挂起的根源.
AllowSynchronousIO
option is disabled by default from .Net core 3.0.0-preview3
in (Kestrel
, HttpSys
, IIS in-process
, TestServer
) because these APIs are source of thread starvation and application hangs.
可以在临时迁移的每个请求上覆盖该选项:
The option can be overridden on a per request for a temporary migration :
var allowSynchronousIoOption = HttpContext.Features.Get<IHttpBodyControlFeature>();
if (allowSynchronousIoOption != null)
{
allowSynchronousIoOption.AllowSynchronousIO = true;
}
您可以找到更多信息并关注 ASP.NET Core 问题跟踪器:AllowSynchronousIO 已全部禁用服务器
You can find more info and follow the ASP.NET Core Issue Tracker : AllowSynchronousIO disabled in all servers
这篇关于缓冲流 - ASP.NET Core 3.0 中不允许同步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!