ASP.NET Core Interview Question #238
How would you stream a large download without loading it fully into memory?
Senior ASP.NET Core Real-World Scenarios Senior Advanced
Quick Interview Answer
Use a stream-based response so the server can transfer data progressively rather than creating a large byte array. The underlying storage API should also support streaming.
Detailed Explanation
Use a stream-based response so the server can transfer data progressively rather than creating a large byte array. The underlying storage API should also support streaming.
Set the correct content type and a safe download file name. Consider range processing when clients need resumable or seekable downloads and the source supports it.
Authorization must be checked before opening protected content, and streams should be disposed correctly by the response pipeline or storage abstraction.
Code Example
[HttpGet("files/{id:guid}")]
public async Task<IActionResult> Download(Guid id, CancellationToken ct)
{
var file = await _store.OpenReadAsync(id, ct);
if (file is null) return NotFound();
return File(
file.Stream,
file.ContentType,
file.DownloadName,
enableRangeProcessing: true);
}