首页 > 解决方案 > 缓冲流 - 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 的情况下更改此代码以工作;

标签: c#asp.net-coreasynchronousasp.net-core-3.1

解决方案


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


推荐阅读