【发布时间】:2021-03-11 20:10:27
【问题描述】:
我有一个 ASP.NET Core 项目,可以下载存储在 SQL Server 中的大文件。它适用于小文件,但大文件通常会在下载之前被读入内存而超时。
所以我正在努力改进它。
基于SQL Client streaming support examples,我已将代码更新为以下内容:
public async Task<FileStreamResult> DownloadFileAsync(int id)
{
ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User);
var file = await this._attachmentRepository.GetFileAsync(id);
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
{
await connection.OpenAsync();
using (SqlCommand command = new SqlCommand("SELECT [Content] FROM [Attachments] WHERE [AttachmentId] = @id", connection))
{
command.Parameters.AddWithValue("id", file.AttachmentId);
SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess);
if (await reader.ReadAsync())
{
if (!(await reader.IsDBNullAsync(0)))
{
Stream stream = reader.GetStream(0);
var result = new FileStreamResult(stream, file.ContentType)
{
FileDownloadName = file.FileName
};
return result;
}
}
}
}
return null;
}
但是当我测试时,它会抛出这个异常:
无法访问已处置的对象。对象名称:'SqlSequentialStream'
有没有办法修复这个异常?
【问题讨论】:
-
测试删除
using,因为它可能会在请求完成之前处理流 -
我测试过,我认为这就是问题所在。我将测试更多以确认。