ASP.NET Core MVC Advanced

Uploading files

Letting users upload files is useful and risky. This lesson shows how to receive files with IFormFile, how to save them safely, and the security checks you should never skip.

A safe file upload
  1. StartUser picks a file<input type="file"> in a multipart/form-data form
  2. Step 2Request is postedThe file arrives with the other form fields
  3. Step 3Model bindingThe file is available as an IFormFile parameter
  4. Step 4Validate itCheck size, allowed extension and file contents
  5. Step 5Save safelyUse a new random file name in a folder outside wwwroot
  6. EndRecord metadataStore the original name, size and path in the database

The idea in plain words

A file upload is a form posted with enctype="multipart/form-data". ASP.NET Core exposes each file as an IFormFile with its name, size, content type and a stream to read it. Small files are buffered in memory or on disk and are easy to handle this way; very large files should be streamed instead.

Treat every uploaded file as hostile. Its name, extension and content type all come from the client and can be faked.

Example: the form

Razor
<form asp-action="Upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" accept=".pdf,.png,.jpg" />
    <button type="submit">Upload</button>
</form>

Example: the action

The file is saved under a random name in a folder that the web server does not serve directly.

C#
private static readonly string[] Allowed = { ".pdf", ".png", ".jpg" };

[HttpPost, ValidateAntiForgeryToken]
[RequestSizeLimit(5_000_000)] // about 5 MB
public async Task<IActionResult> Upload(IFormFile? file)
{
    if (file is null || file.Length == 0)
        ModelState.AddModelError("file", "Choose a file.");
    else if (!Allowed.Contains(Path.GetExtension(file.FileName).ToLowerInvariant()))
        ModelState.AddModelError("file", "Only PDF, PNG and JPG files are allowed.");

    if (!ModelState.IsValid) return View();

    var folder = Path.Combine(_env.ContentRootPath, "uploads"); // not wwwroot
    Directory.CreateDirectory(folder);
    var path = Path.Combine(folder, Path.GetRandomFileName());
    await using var stream = System.IO.File.Create(path);
    await file!.CopyToAsync(stream);

    return RedirectToAction(nameof(Index));
}

Common mistakes

  • Using file.FileName as the path on disk, which allows path tricks and overwrites.
  • Saving uploads in wwwroot, where they can be downloaded or even executed.
  • Trusting the extension or ContentType only. Check file signatures for important file types and scan files when possible.
  • Forgetting enctype="multipart/form-data", so the action receives null.

Interview question

What security checks should you apply to file uploads in ASP.NET Core?

Limit the file size, allow only specific extensions and verify the file signature, never use the client-supplied file name as the storage path (generate a random name), store files outside wwwroot or in separate storage, require authentication where appropriate, protect the form with an anti-forgery token, and scan files for malware if they are shared with other users.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.