skip to content

When an ASP.NET Core 10 app saves uploaded IFormFile documents, which values are untrusted and how should the files be stored?

level: middleimportance: should knowfreq 45%

answer

  1. FileName and ContentType are client claims
  2. Path.GetRandomFileName for the stored name
  3. outside wwwroot
  4. extension allow-list plus file signature
  5. HTML-encode the original name on display

basics

~20 s

FileName and ContentType come from the client. Store each file under a server-generated name such as Path.GetRandomFileName(), outside wwwroot, after checking size, an extension allow-list and the file signature; keep the original name only as encoded metadata.

solid answer

~40 s

`IFormFile.FileName` and `IFormFile.ContentType` are copied from the part's headers, so the client controls both; only `Length` is measured. Never build a storage path from `FileName`: generate the name with `Path.GetRandomFileName()` or a GUID and keep the original name in a database column, HTML-encoded when shown (Razor encodes automatically; elsewhere use `WebUtility.HtmlEncode`). Store files outside the web root, on a separate volume or in object storage, so `UseStaticFiles` can never serve them and they are never executed. Validate before accepting: size limits, an allow-list of extensions, and the file signature in the first bytes, because a renamed executable keeps its real header. Then scan for malware, and serve downloads through an authorized action with an explicit content type and `Content-Disposition: attachment`.

code

csharp · 16 lines
csharp
static readonly Dictionary<string, byte[]> Signatures = new()
{
    [".pdf"] = "%PDF"u8.ToArray(),
    [".png"] = [0x89, 0x50, 0x4E, 0x47],
};

static async Task<bool> LooksValidAsync(IFormFile file, CancellationToken ct)
{
    var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
    if (!Signatures.TryGetValue(ext, out var magic) || file.Length < magic.Length) return false;

    await using var s = file.OpenReadStream();
    var head = new byte[magic.Length];
    await s.ReadExactlyAsync(head, ct);
    return head.AsSpan().SequenceEqual(magic);
}

go deeper

for a junior

Recall that FileName and ContentType come from the client and that stored files get generated names outside wwwroot.

for a middle

Explain the validation order (size, extension, signature, scan), where metadata lives, and how the original name is encoded on display.

for a senior

Design storage for sensitive documents: separate volume or object storage, quarantine until scanned, authorized downloads and audit metadata.

for a principal

Own the policy for regulated uploads, from retention and encryption to which formats are accepted at all, and how exceptions are approved.

## What the server actually knows about an upload In the telehealth app, clinics upload scanned medical records as PDFs or images. Each `IFormFile` comes from one part of a multipart body, and most of what it reports was written by the client: | Member | Source | Use it for | |---|---|---| | `FileName` | the part's `Content-Disposition` header | display only, after encoding | | `ContentType` | the part's `Content-Type` header | a hint; verify the bytes | | `Length` | bytes the server buffered | size checks | | content | the bytes themselves | signature check, scanning | A client can send `FileName = "report.pdf"` with an executable inside, or a name containing path segments or markup. The documentation's rule is blunt: never use a client-supplied file name for saving a file to physical storage. ## Naming and placing the stored file 1. **Generate the name.** `Path.GetRandomFileName()` returns a random name with no directory part; a `Guid` works too. 2. **Store outside the web root.** Anything under `wwwroot` can be served by the static files middleware. Use a directory from configuration on its own volume, or object storage, or a database column for small files. 3. **Keep metadata separately.** Record the original name, the declared type, the patient record, the uploader and a hash in the database, linked by the generated name. 4. **No execute permission** on the storage location, and a quota per user or tenant. ## Validating the content - **Size first:** reject zero-length files and anything over the per-endpoint maximum before reading further. - **Extension allow-list:** check `Path.GetExtension(file.FileName)` against `.pdf`, `.png`, `.jpg`; this is only a first filter, because the extension is part of the client's claim. - **File signature:** read the first bytes with `OpenReadStream()` and compare them with the format's signature (for example `%PDF` for PDF). A renamed executable fails here. - **Malware scanning:** hand the stored file to a scanner before it becomes visible to other users; quarantine until it passes. - **Re-encode images** when practical, which strips embedded payloads and metadata. ## Displaying and serving - Razor encodes `@record.OriginalName` automatically; outside Razor, call `WebUtility.HtmlEncode` before writing a client-supplied name into HTML. - Serve files through an action that checks authorization for that patient record, sets the stored content type, and adds `Content-Disposition: attachment` (the `fileDownloadName` argument of `File` or `PhysicalFile`). - Never redirect to a public URL of the storage folder. ## Where each check runs 1. **Before binding:** `[RequestSizeLimit]` and `[RequestFormLimits]` bound the whole body and each part, so an oversized file never reaches your validation code. 2. **In the action:** the size, extension and signature checks, before anything is written to permanent storage. 3. **After storage:** malware scanning and quarantine, with the record marked pending until it passes. Keep these checks in one service of your own, so a controller and a Minimal API endpoint apply the same rules. Log the generated name together with the uploader and the declared name, but never the file contents of a medical record. ## A compact checklist | Step | ASP.NET Core piece | |---|---| | Bound the size | `[RequestSizeLimit]`, `[RequestFormLimits]`, a `Length` check | | Name the file | `Path.GetRandomFileName()` | | Place it | a configured path outside `IWebHostEnvironment.WebRootPath` | | Check the bytes | `OpenReadStream()` plus a signature table | | Show the name | Razor encoding or `WebUtility.HtmlEncode` | | Serve it | an authorized action returning `PhysicalFile` or `File` with a download name |

  • Why is storing uploads under wwwroot a problem even with random file names?
    `UseStaticFiles` serves everything under the web root to anyone who knows or guesses the URL, bypassing your authorization checks; for medical records that is a data leak. Store files outside `WebRootPath` and serve them only through an action that authorizes the caller and sets the content type and download name.
  • Is checking IFormFile.ContentType enough to reject an executable disguised as a PDF?
    No. `ContentType` is whatever the client wrote in the part's header, and a client can label any bytes `application/pdf`. Read the first bytes with `OpenReadStream()` and compare them with the PDF signature, then scan the file; the declared type is at most a quick first filter.

  • IFormFile.ContentType is detected by ASP.NET Core from the file's bytes.
  • Keeping the client's FileName is fine once spaces are removed.
  • Uploads belong in wwwroot so they can be downloaded easily.
  • A matching extension proves the file is the format it claims.
  • Random stored names make authorization on downloads unnecessary.