ActionResult returning a Stream

Having an action call another action is a design smell. You should avoid it. Simply put the logic that needs to be reused between the 2 actions in a service layer. And then call this logic from your 2 actions.

For example:

public ActionResult Action1()
{
    Stream stream = service.GetStream();
    // ... do something with the stream and return a view for example
    return View();
}

public ActionResult Action2()
{
    Stream stream = service.GetStream();
    // let's return the stream to the client so that he could download it as file
    return File(stream, "application/pdf");
}

Now you no longer need to call the second action from the first one.


The shortest way to use a Stream as the result of an Action Method in a Controller is the one you already showed in the question: use the File helper method of Controller. This returns a FileStreamResult.

There are a couple of overloads available that take a Stream. Both overloads require the MIME type of the response to be specified, which will be emitted as the Content-Type header of the response; if your circumstances are such that this is unknown to your application, you could always specify text/plain or application/octet-stream for arbitrary text or binary data, respectively. One overload additionally takes a third parameter that sets the filename to show in the browser's download dialogue (controlled via the Content-Disposition header), if applicable.

Overload signatures:

protected internal FileStreamResult File(
    Stream fileStream,
    string contentType
)

and

protected internal virtual FileStreamResult File(
    Stream fileStream,
    string contentType,
    string fileDownloadName
)

Example usage:

return File(myStream, "application/pdf");

or

return File(myStream, "application/pdf", "billing-summary.pdf");

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")

Tags:

C#

Asp.Net Mvc