ASP.NET Core MVC Interview Question #46
How do you return a file from an ASP.NET Core MVC action?
Controllers, Actions, Model Binding & Action Results Junior Beginner
Quick Interview Answer
Controller.File provides overloads for returning file bytes, streams, or physical/virtual files with an appropriate content type and optional download filename. File responses are useful for generated reports, documents, images, and exports.
Detailed Explanation
Controller.File provides overloads for returning file bytes, streams, or physical/virtual files with an appropriate content type and optional download filename. File responses are useful for generated reports, documents, images, and exports.
Validate authorization and file identifiers carefully. Never allow untrusted input to be turned directly into arbitrary server file paths.
Code Example
public IActionResult Download()
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("Report");
return File(
data,
"text/plain",
"report.txt");
}