Aspnetcore: What is the proper way to dispose a filestream in MVC?

Created on 5 Feb 2019  路  3Comments  路  Source: dotnet/aspnetcore

We have the following code in several places in our codebase:

[Route("api/[controller]")]
public class DownloadController : Controller {

    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) 
    {
        Memorystream stream = await {{ get memorystream somehow, most of the time this is an excel sheet generated in memory by using epplus }}

        if(stream == null)
        {
            return NotFound();
        }

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

Due to company policy, our application is scanned by a static code scanner that has a problem with the stream that is not in a using statement. We never had any performance problems, and adding a using statement breaks the return because it is disposing the stream prematurely. We searched around, but cannot find a best practice for disposing the stream in a timely manner.

Can someone tell me what we should do? Or is the current implementation oke and will the GC kick in right after the file has been returned to the user?

area-mvc

Most helpful comment

This isn't really the place for a question like this, more suited for Stack Overflow, but underneath the covers File is shorthand in the base controller for "New FileStreamResult," which will dispose your stream, so this is fine, I believe.
https://stackoverflow.com/questions/13983190/actionresult-returning-a-stream

All 3 comments

This isn't really the place for a question like this, more suited for Stack Overflow, but underneath the covers File is shorthand in the base controller for "New FileStreamResult," which will dispose your stream, so this is fine, I believe.
https://stackoverflow.com/questions/13983190/actionresult-returning-a-stream

That's right, MVC does it on your behalf.

Closing since this has been answered.

Was this page helpful?
0 / 5 - 0 ratings