Secure file upload in ASP.NET Core 10: request size limits, streaming, extension allow-lists plus magic-number checks, generated storage names, private Blob containers with short-lived user-delegation SAS, quarantine and malware scanning, and safe download headers.
File upload is one of the riskiest features: attackers use it for DoS (huge files), stored XSS (HTML or SVG served back), web shells (files under the web root), path traversal through file names, and malware delivered to staff. I set size limits at Kestrel and per endpoint, then stream the body rather than buffering it. I validate with an extension allow-list plus a magic-number check, because the extension and Content-Type are attacker-controlled. The stored name is a generated GUID; the original name is only sanitised metadata. Files go to a private Blob container, first into quarantine, are malware-scanned (Defender for Storage), and only then promoted. Downloads use a short-lived user-delegation SAS or an authorised endpoint with Content-Disposition: attachment and nosniff. The trade-off is latency: scanning makes upload asynchronous, so the UI must show a "processing" state.
"I treat every uploaded file as hostile. The risks are denial of service from very large or very many files, stored XSS if we ever serve an HTML or SVG file back from our own origin, remote code execution if a file lands somewhere the web server executes it, path traversal if the client's file name reaches
Path.Combine, and malware that a staff member later opens. Then there are parser bugs: image libraries and PDF parsers have had plenty of CVEs, so processing untrusted files is itself risky.In ASP.NET Core I put limits in layers: Kestrel's
MaxRequestBodySize, a per-endpointRequestSizeLimitand form limits, plus rate limiting and per-user quotas. I stream the multipart body straight to Blob Storage withMultipartReaderorIFormFile.OpenReadStream()instead of reading it into a byte array. I validate against an allow-list of extensions and check the first bytes against the expected signature -%PDF-, the PNG header,FF D8 FFfor JPEG - because theContent-Typeheader and the file name are just strings the attacker chose. The blob name is a GUID; the original name goes into metadata after sanitising. Uploads land in a private quarantine container, Defender for Storage malware scanning tags them, and an Event Grid-triggered function moves clean files to the real container and deletes malicious ones.For downloads I never make containers public. Either the API checks authorisation and streams the file with
Content-Disposition: attachmentandX-Content-Type-Options: nosniff, or it hands out a user-delegation SAS valid for a few minutes for that one blob. The mistake I see is checking only the extension and saving towwwroot/uploads, which turns an upload form into a web shell or an XSS host. The senior point is that uploads are a pipeline - limit, validate, quarantine, scan, promote, serve safely - not a singleSaveAscall."
| Threat | Example | Control |
|---|---|---|
| DoS | 5 GB upload, thousands of small uploads, zip bomb | Kestrel and endpoint size limits, streaming, rate limiting, quotas, don't decompress untrusted archives without limits |
| Stored XSS | invoice.html or SVG with script served inline |
Allow-list, Content-Disposition: attachment, nosniff, separate user-content domain, CSP |
| Web shell / RCE | shell.aspx saved under the web root |
Store outside the web root (Blob), never execute uploads |
| Path traversal | file name ..\..\appsettings.json |
Generated names, never use client file names in paths |
| Malware | Macro-laden document opened by staff | Quarantine and scan before promotion |
| Parser exploits | Malformed image triggers a library CVE | Patch libraries, process in an isolated worker, re-encode images |
| IDOR on download | /files/123 fetches another user's file |
Authorise per file; unguessable ids are not authorisation |
| CSRF | Cookie-authenticated upload form | Antiforgery tokens (on by default for form-bound Minimal API endpoints in .NET 8+) |
| Signal | Trust | Use |
|---|---|---|
IFormFile.FileName |
None | Display only, after sanitising |
IFormFile.ContentType |
None | Ignore for security decisions |
| Extension | Low | Allow-list as a first filter |
| Magic number (first bytes) | Medium | Confirms the format family |
| Full parse / re-encode | Higher | Images: re-encode to strip payloads; PDFs: sanitise if feasible |
| Malware scan | Higher | Required before anyone opens the file |
[A claims portal] previously saved uploads to wwwroot/uploads with the original file name. After moving to a streamed upload into a quarantine container with Defender for Storage scanning, memory per upload dropped from [~the file size] to [~80 KB of buffers], and in the first [quarter] the scanner blocked [N] malicious files that would previously have reached claims assessors.
Checks whether the candidate sees file upload as a multi-threat feature and knows the concrete ASP.NET Core and Azure controls.
Green flags
Red flags
client --multipart/form-data--> Kestrel (MaxRequestBodySize, default ~28.6 MB)
|
v
endpoint metadata (RequestSizeLimit, form limits)
|
+-------------------------+-------------------------+
| IFormFile binding | MultipartReader (streaming)
| form read into memory up to 64 KB, | sections read one by one,
| then buffered to temp files on disk | you copy the stream directly
| (FormOptions.MultipartBodyLengthLimit 128 MB) | to Blob Storage
v v
simple, fine for small files needed for large files, low memory
Key settings:
KestrelServerOptions.Limits.MaxRequestBodySize - global cap (default 30,000,000 bytes).[RequestSizeLimit], [DisableRequestSizeLimit], or IHttpMaxRequestBodySizeFeature - per endpoint.FormOptions (MultipartBodyLengthLimit, ValueCountLimit, MultipartHeadersLengthLimit) - form parsing limits, settable per endpoint with [RequestFormLimits].maxAllowedContentLength in web.config.| Format | Signature (hex) | ASCII |
|---|---|---|
25 50 44 46 2D |
%PDF- |
|
| PNG | 89 50 4E 47 0D 0A 1A 0A |
.PNG.... |
| JPEG | FF D8 FF |
|
| ZIP / DOCX / XLSX | 50 4B 03 04 |
PK.. |
| GIF | 47 49 46 38 |
GIF8 |
Signatures confirm the format family, not safety: a valid PDF can contain malicious JavaScript, a DOCX can contain macros (DOCM masquerading), and polyglot files are valid in two formats. That's why scanning and safe serving still matter.
API --stream--> [quarantine container, private]
| Defender for Storage on-upload malware scanning
| -> blob index tag: Malware Scanning scan results
v
Event Grid (scan result event)
|
v
Function: clean? copy to [documents] + delete original
malicious? delete or move to [infected], alert
|
Client <--user-delegation SAS (5 min, read, one blob)-- API (after authorisation)
Content-Disposition and Content-Type on the blob (or as SAS response overrides) so browsers download rather than render.usercontent.example.com.au) isolates any rendering from your app's cookies and origin... or absolute paths (zip slip).Uploaded identity documents and medical records are personal and often sensitive information: APP 11 applies, they're prime NDB material, and they should be retained only as long as needed. Remove EXIF location from photos to avoid collecting information you didn't intend to. For government systems, the ISM includes controls on content filtering and malware scanning of files from external sources.
dotnet-counters monitor while uploading via IFormFile versus streaming with MultipartReader..html file to .png and confirm your magic-number check rejects it.Vulnerable: saves under the web root with the client's file name and trusts the Content-Type:
app.MapPost("/upload", async (IFormFile file, IWebHostEnvironment env) =>
{
if (file.ContentType != "application/pdf") return Results.BadRequest(); // attacker sets this header
var path = Path.Combine(env.WebRootPath, "uploads", file.FileName); // ..\..\ or shell.aspx
await using var fs = File.Create(path);
await file.CopyToAsync(fs);
return Results.Ok($"/uploads/{file.FileName}"); // served inline from our origin
});
Exploit in one line: upload x.html with Content-Type: application/pdf containing a script, then send staff the /uploads/x.html link (stored XSS), or use a traversal file name to overwrite files.
Fixed: limits, allow-list plus signature check, generated name, private quarantine container:
namespace Claims.Api;
public static class UploadEndpoints
{
private static readonly Dictionary<string, byte[][]> Allowed = new(StringComparer.OrdinalIgnoreCase)
{
[".pdf"] = ["%PDF-"u8.ToArray()],
[".png"] = [[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]],
[".jpg"] = [[0xFF, 0xD8, 0xFF]],
[".jpeg"] = [[0xFF, 0xD8, 0xFF]],
};
public static void Map(WebApplication app)
{
app.MapPost("/claims/{claimId:guid}/documents", UploadAsync)
.RequireAuthorization("ClaimOwner")
.RequireRateLimiting("uploads")
.WithMetadata(new RequestSizeLimitAttribute(10 * 1024 * 1024)); // 10 MB for this endpoint only
}
private static async Task<IResult> UploadAsync(
Guid claimId, IFormFile file, BlobContainerClient quarantine, CancellationToken ct)
{
var ext = Path.GetExtension(file.FileName);
if (!Allowed.TryGetValue(ext, out var signatures))
return Results.Problem("File type not allowed.", statusCode: 415);
await using var input = file.OpenReadStream();
var header = new byte[8];
var read = await input.ReadAtLeastAsync(header, header.Length, throwOnEndOfStream: false, ct);
if (!signatures.Any(s => read >= s.Length && header.AsSpan(0, s.Length).SequenceEqual(s)))
return Results.Problem("File content does not match its type.", statusCode: 415);
input.Position = 0; // IFormFile streams are seekable (buffered); use MultipartReader for very large files
var blobName = $"{claimId}/{Guid.NewGuid():N}{ext.ToLowerInvariant()}"; // never the client's name
var blob = quarantine.GetBlobClient(blobName);
await blob.UploadAsync(input, new BlobUploadOptions
{
HttpHeaders = new BlobHttpHeaders
{
ContentType = ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase) ? "application/pdf" : $"image/{ext.TrimStart('.').ToLowerInvariant().Replace("jpg", "jpeg")}",
ContentDisposition = "attachment"
},
Metadata = new Dictionary<string, string>
{
["originalName"] = Uri.EscapeDataString(Path.GetFileName(file.FileName)) // display only
}
}, ct);
// Status stays 'Scanning' until the Defender scan result event promotes the blob.
return Results.Accepted(value: new { documentId = blobName, status = "Scanning" });
}
}
Issuing a short-lived, single-blob download link after authorisation:
public sealed class DownloadLinks(BlobServiceClient service)
{
public async Task<Uri> CreateAsync(BlobClient blob, CancellationToken ct)
{
var now = DateTimeOffset.UtcNow;
var key = await service.GetUserDelegationKeyAsync(now.AddMinutes(-1), now.AddMinutes(10), ct);
var sas = new BlobSasBuilder(BlobSasPermissions.Read, now.AddMinutes(5))
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name,
Resource = "b",
ContentDisposition = "attachment"
};
return new BlobUriBuilder(blob.Uri) { Sas = sas.ToSasQueryParameters(key.Value, service.AccountName) }.ToUri();
}
}
IFormFile.ContentType or the extension alone. Why it is wrong: Both are attacker-controlled strings. Instead: Use an extension allow-list plus a file-signature check, then scan.wwwroot. Why it is wrong: Files become directly reachable and may be served inline or, with misconfiguration, executed. Instead: Store in a private Blob container and serve through authorisation or short-lived SAS.CopyToAsync(MemoryStream) or ToArray(). Why it is wrong: A few concurrent large uploads exhaust memory and land on the LOH. Instead: Stream to storage and set size limits.MaxRequestBodySize globally for one upload endpoint. Why it is wrong: Every endpoint now accepts huge bodies, widening DoS exposure. Instead: Raise the limit per endpoint.Content-Disposition: attachment, nosniff, and ideally a separate user-content domain.A senior engineer designs upload as an asynchronous pipeline with explicit states (Uploaded -> Scanning -> Clean / Rejected) because that's what makes scanning, image re-encoding and retention possible without blocking requests. They also push most of the heavy lifting to managed services: Blob Storage for durable, private storage, Defender for Storage for scanning, and SAS for delegated downloads, so the API process never holds large files in memory or runs risky parsers.
Trade-offs to name: scanning adds seconds to minutes of latency and costs per GB scanned; direct-to-Blob uploads with a write-only SAS remove load from the API but move validation after the upload, so the quarantine step becomes mandatory. Measure: upload p95 latency, memory per upload, scan latency, and blocked files per month.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
Upload through the API (IFormFile) |
Small files (< 10 MB), simple flows | API bandwidth and memory | Large media files |
Streamed through the API (MultipartReader) |
Larger files needing server-side checks before storage | More code | Very high volumes |
| Direct to Blob with write-only SAS | Large files, high volume | Validation only after upload; quarantine mandatory | When you must reject before storing |
| Defender for Storage malware scanning | Any user-supplied files on Azure | Per-GB scanning cost | Files never opened by people or other systems (rare) |
It is a path traversal vulnerability. file=../../../etc/passwd resolves outside the reports folder, and file=/etc/passwd is worse: Path.Combine discards the base path when the second argument is rooted. The endpoint also has no authorisation and leaks whether files exist.
Fix: do not let users name files. Map an ID to a stored path (database), or if names are required, take only Path.GetFileName(file), build the path, Path.GetFullPath it and check it starts with the root plus a separator, using the platform's case rules. Serve through PhysicalFileProvider or Results.File with the checked path, and add authorisation.
Set limits at every layer and fail fast with a clear status. Lower Kestrel's MaxRequestBodySize (default about 28.6 MB) globally, and per endpoint with [RequestSizeLimit]; requests over the limit get 413 Payload Too Large. Set FormOptions limits for multipart. Keep System.Text.Json's MaxDepth (64 by default; lower it for shallow contracts), so deeply nested JSON fails with 400. Validate collection counts in FluentValidation or data annotations and return a ValidationProblem. Stream large uploads instead of buffering, and add rate limiting (AddRateLimiter) so repeated large requests can't exhaust CPU and memory (a denial-of-service vector).
XSS is when attacker-controlled input is rendered as script in your page, so it runs in your origin with the victim's session: it can read the DOM, call your API as the user and steal tokens kept in localStorage. Stored XSS is saved and served to other users; reflected echoes request input back; DOM-based happens entirely in client-side JavaScript (innerHTML, location.hash).
Razor's @ HTML-encodes by default, which stops most of it. The gaps are the escape hatches (Html.Raw, HtmlString, React's dangerouslySetInnerHTML, Blazor's MarkupString) and wrong contexts: HTML encoding doesn't make a value safe inside a <script> block or an href="javascript:...". Rich text needs an allow-list sanitiser. A CSP with nonces is the safety net, not the fix.
How to tell it (STAR)
**S:** Our claims portal saved customer uploads under the web root, and assessors viewed them on the same origin. **T:** A pen test found stored XSS through uploaded SVGs, and I [owned] the fix. **A:** I closed it the same day by blocking SVG and forcing downloads, then rebuilt uploads as a pipeline: size limits, signature checks, generated names, a private quarantine container with malware scanning, and five-minute SAS links from a separate domain. **R:** The retest found [no issues], upload memory dropped [to a few KB of buffers per upload], and the scanner has since blocked [N] malicious files before any assessor opened them.
Last updated 23 Nov 2026.