– How to present a file for download from an MVC controller

In WebForms, I would normally have code like this to let the browser present a "Download File" popup with an arbitrary file type, like a PDF, and a filename:

''# Send the file to the output stream
Response.Buffer = True

Response.AddHeader("Content-Length", pdfData.Length.ToString())
Response.AddHeader("Content-Disposition", "attachment; filename= " & Server.HtmlEncode(filename))

''# Set the output stream to the correct content type (PDF).
Response.ContentType = "application/pdf"

''# Output the file

''# Flushing the Response to display the serialized data
''# to the client browser.

How do I accomplish the same task in ASP.NET MVC?

Best Solution

Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly.

public ActionResult GetPdf(string filename)
    return File(filename, "application/pdf", Server.UrlEncode(filename));