将MemoryStream作为ActionResult返回时,它是否会被自动处理?

Sea*_*son 12 c# asp.net-mvc jquery memorystream using

public ActionResult CustomChart(int reportID)
{
    Chart chart = new Chart();

    // Save the chart to a MemoryStream
    var imgStream = new MemoryStream();
    chart.SaveImage(imgStream);
    imgStream.Seek(0, SeekOrigin.Begin);

    // Return the contents of the Stream to the client
    return File(imgStream, "image/png");
}
Run Code Online (Sandbox Code Playgroud)

我习惯于将"using"语句与MemoryStreams结合使用.这是不是必须使用'使用'语句的情况吗?或者在'using'语句中调用return是否有效?

编辑:

出于我的目的,我发现引入'using'语句不起作用(抛出ObjectDisposedException).这是我在客户端做的事情:

$('#ReportTest').bind('load', function () {
                        $('#LoadingPanel').hide();
                        $(this).unbind('load');
                    }).bind('error', function () {
                        $('#LoadingPanel').hide();
                        $(this).unbind('error');
                    }).attr('src', '../../Chart/CustomChart?ReportID=' + settings.id);
Run Code Online (Sandbox Code Playgroud)

vcs*_*nes 23

将MemoryStream作为ActionResult返回时,它是否会被自动处理?

是的,MVC(至少版本3)将为您清理它.你可以采取看看源的的WriteFile的方法FileStreamResult:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该行将using (FileStream) {Stream放入一个使用块中,从而在将内容写入Http Response时将其置于处理状态.

您还可以通过创建执行此操作的虚拟流来验证此行为:

public class DummyStream : MemoryStream
{
    protected override void Dispose(bool disposing)
    {
        Trace.WriteLine("Do I get disposed?");
        base.Dispose(disposing);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以MVC 处理它.