Does a Stream get Disposed when returning a File from an Action?(从动作返回文件时,流会被释放吗?)
问题描述
我正在向 MemoryStream
写入一个字符串,我需要将流返回到控制器操作,以便我可以将其作为文件发送出去以供下载.
I'm writing a string to a MemoryStream
I need to return the stream to the Controller Action so I can send it off as a file for download.
通常,我将 Stream 包装在 using 语句中,但在这种情况下,我需要返回它.我退货后它仍然会被丢弃吗?还是我需要以某种方式自己处理它?
Normally, I wrap the Stream in a using statement, but, in this case, I need to return it. Does it still get Disposed after I return it? Or do I need to dispose it myself somehow?
//inside CsvOutputFormatter
public Stream GetStream(object genericObject)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream, Encoding.UTF8);
writer.Write(_stringWriter.ToString());
writer.Flush();
stream.Position = 0;
return stream;
}
返回文件的控制器动作:
Controller Action that returns the file:
[HttpGet]
[Route("/Discussion/Export")]
public IActionResult GetDataAsCsv()
{
var forums = _discussionService.GetForums(_userHelper.UserId);
var csvFormatter = new CsvOutputFormatter(new CsvFormatterOptions());
var stream = csvFormatter.GetStream(forums);
return File(stream, "application/octet-stream", "forums.csv");
//is the stream Disposed here automatically?
}
推荐答案
这里根据源码 aspnet/AspNetWebStack/blob/master/src/System.Web.Mvc/FileStreamResult.cs
protected override void WriteFile(HttpResponseBase response)
{
// grab chunks of data and write to the output stream
Stream outputStream = response.OutputStream;
using (FileStream)
{
byte[] buffer = new byte[BufferSize];
while (true)
{
int bytesRead = FileStream.Read(buffer, 0, BufferSize);
if (bytesRead == 0)
{
// no more data
break;
}
outputStream.Write(buffer, 0, bytesRead);
}
}
}
FileStream
将是您调用时传递的流
Where FileStream
would have been the stream passed when you called
return File(stream, "application/octet-stream", "forums.csv");
更新.
您的问题最初被标记为 Asp.Net MVC,但代码看起来像是更新的核心框架.
Your question was originally tagged as Asp.Net MVC but the code looks like the more recent core framework.
在那里也找到了它,虽然写法不同,但它在技术上做同样的事情.
Found it there as well though written differently it does the same thing technically.
aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs
protected static async Task WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, long rangeLength)
{
var outputStream = context.Response.Body;
using (fileStream)
{
try
{
if (range == null)
{
await StreamCopyOperation.CopyToAsync(fileStream, outputStream, count: null, bufferSize: BufferSize, cancel: context.RequestAborted);
}
else
{
fileStream.Seek(range.From.Value, SeekOrigin.Begin);
await StreamCopyOperation.CopyToAsync(fileStream, outputStream, rangeLength, BufferSize, context.RequestAborted);
}
}
catch (OperationCanceledException)
{
// Don't throw this exception, it's most likely caused by the client disconnecting.
// However, if it was cancelled for any other reason we need to prevent empty responses.
context.Abort();
}
}
}
这篇关于从动作返回文件时,流会被释放吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从动作返回文件时,流会被释放吗?


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01