You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用ReadAsync遇NotSupportedException:存在未完成读取操作

问题解决:NotSupportedException 读取操作冲突

异常信息

NotSupportedException: The ReadAsync method cannot be called when another read operation is pending.

问题原因

你代码里的核心问题有两个:

  1. HttpClient.GetStreamAsync返回的网络流不支持并发读取,ASP.NET Core的FileStreamResult在输出响应时会尝试异步读取该流,和流本身的读取操作产生冲突;
  2. 用using声明的HttpClient和Stream会在方法执行完毕后立即被释放,而FileStreamResult是在方法返回后才开始处理流的,调试时因为断点延迟了释放时机,所以能正常运行。

修复代码

public async Task<IActionResult> Downloadfile(string userId, CancellationToken ct)
{
    string docId = $"tinyurl:{userId}";
    DocumentResponse response1 = await blobManager.GetCustomUrlByUserId(docId, ct);
    TinyUrl tinyUrl = JsonConvert.DeserializeObject<TinyUrl>(response1.Content);

    using HttpClient wc = new();
    using Stream stream = await wc.GetStreamAsync(tinyUrl.ActualUrl, ct);
    
    // 将网络流复制到内存流,避免并发读取冲突
    var memoryStream = new MemoryStream();
    await stream.CopyToAsync(memoryStream, ct);
    memoryStream.Position = 0; // 重置流位置到开头,确保能被正确读取
            
    return new FileStreamResult(memoryStream, "application/zip");           
}

关键说明

  • MemoryStream支持多次异步读取,不会触发读取冲突的异常;
  • 不需要给MemoryStream添加using,FileStreamResult会在响应处理完成后自动释放它;
  • 把CancellationToken传递给GetStreamAsync和CopyToAsync,确保操作能响应外部取消信号。

内容的提问来源于stack exchange,提问作者Jug Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:12:46