从动作返回文件时,流是否被丢弃? [英] Does a Stream get Disposed when returning a File from an Action?

查看:102
本文介绍了从动作返回文件时,流是否被丢弃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将字符串写入MemoryStream,我需要将流返回到Controller Action,以便可以将其作为文件发送出去进行下载.

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?
}

推荐答案

根据此处的源代码

According to source code here 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);
        }
    }
}

在您调用

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();
        }
    }
}

这篇关于从动作返回文件时,流是否被丢弃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆