Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionResult returning a Stream

Tags:

c#

asp.net-mvc

My ActionResult returns a File but I also need it to conditionally return a Stream.

I have not been able to find documentation on how an ActionResult can return a Stream.

Here is my code for return of a file:

    return File(memoryStream,.... ) 

As mentioned, I need to return just a Stream.

like image 961
Nate Pet Avatar asked Dec 21 '12 01:12

Nate Pet


People also ask

How do I return a streamed file?

To return a file stream, you can use a FileStreamResult. This lets you specify the stream, the MIME type, and some other options (like the file name). // the stream when the transfer is complete.

Does FileStreamResult close stream?

Yes. It uses a using block around the stream, and that ensures that the resource will dispose.


1 Answers

Updated for MVC5 2020:

my previous answer was dated.

as of now, the File returns different type of ActionResult depends on given arguments

// to return FileStreamResult return File(memoryStream, "application/pdf"); // or.. return File(memoryStream, "application/pdf", "file_name"); 

Use FileStreamResult:

MemoryStream stream = someService.GetStream();  return new FileStreamResult(stream, "application/pdf") 
like image 64
aifarfa Avatar answered Sep 21 '22 17:09

aifarfa