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

BsonDocument转MemoryStream返回API响应时遇流异常求助

问题解决方法

核心原因

  • 用using包裹MemoryStream时,方法返回前流就会被释放,后续FileStreamResult处理响应时自然会报错“无法访问已关闭的流”。
  • 不用using时出现“不支持超时”,大概率是因为image.File!["Content"].AsByteArray是延迟加载的字节数据——当方法返回后,数据库连接已释放,后续读取流时无法从数据库获取完整数据,触发超时。

修复代码

先把Bson中的字节数据完整复制到本地数组,再基于这个数组创建MemoryStream,彻底脱离对数据库连接的依赖:

private Task<FileStreamResult> GetImageStream(Domain.Entities.Courses.Image image)
{
    // 先把延迟加载的字节数据复制到本地数组
    var contentBytes = image.File!["Content"].AsByteArray.ToArray();
    var ms = new MemoryStream(contentBytes);

    ms.Seek(0, SeekOrigin.Begin);
    return Task.FromResult(new FileStreamResult(ms, image.File!["ContentType"].ToString())
    {
        FileDownloadName = image.File!["FileName"].ToString()
    });
}

补充说明

  • 因为方法内没有异步操作,不需要async关键字,直接用Task.FromResult返回结果即可。
  • FileStreamResult会在ASP.NET Core的响应管道中自动负责释放MemoryStream,不需要手动用using管理。

内容的提问来源于stack exchange,提问作者Fawad Baig

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:07:04