Secure File Upload in ASP.NET Core: Limits, Checks and Storage
Secure file upload in ASP.NET Core: size limits, magic-byte checks, random names, blob storage, presigned URLs, malware scans and rate limits that work.
By Victor Sanchez
Secure file upload in ASP.NET Core is harder than it looks, because an upload endpoint accepts arbitrary bytes and a file name chosen by a stranger. In the applications we remediate, scanners flag the same issues again and again: the client's file name used as a path, no size limit, extension checks only, and files saved inside the web root where they can be served or even executed. Each of those turns a "simple" document upload into path traversal, stored XSS or a denial of service.
What can go wrong with a file upload?
- Path traversal: a name like
..\..\web.configoverwrites files outside the upload folder. - Executable content: an
.aspx,.htmlor.svgwith script, served from your own domain. - Resource exhaustion: huge bodies, zip bombs or thousands of small uploads.
How to limit upload size in Kestrel and IIS
Per Microsoft's documentation, Kestrel's default maximum request body size is 30,000,000 bytes (about 28.6 MB), and IIS has the same default through maxAllowedContentLength. Multipart bodies have their own limit, FormOptions.MultipartBodyLengthLimit, which defaults to 128 MB. Set limits to what your feature really needs, as close to the endpoint as possible:
// Program.cs: global defaults
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 10 * 1024 * 1024);
builder.Services.Configure<FormOptions>(o => o.MultipartBodyLengthLimit = 10 * 1024 * 1024);
// Per endpoint: 5 MB for this feature
[HttpPost("documents")]
[RequestSizeLimit(5 * 1024 * 1024)]
public async Task<IActionResult> Upload(IFormFile file, CancellationToken ct) { ... }
<!-- web.config when hosting behind IIS (bytes) -->
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="10485760" />
</requestFiltering>
</security>
</system.webServer>
How to validate file type: extension and magic bytes
The Content-Type header and the extension are both supplied by the client. Use an allowlist of extensions, then confirm the first bytes of the file (its signature) match the expected format:
private static readonly Dictionary<string, byte[][]> Signatures = new(StringComparer.OrdinalIgnoreCase)
{
[".pdf"] = [[0x25, 0x50, 0x44, 0x46]], // %PDF
[".png"] = [[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]],
[".jpg"] = [[0xFF, 0xD8, 0xFF]],
[".jpeg"] = [[0xFF, 0xD8, 0xFF]]
};
public static async Task<bool> IsAllowedAsync(IFormFile file, CancellationToken ct)
{
var ext = Path.GetExtension(file.FileName);
if (string.IsNullOrEmpty(ext) || !Signatures.TryGetValue(ext, out var expected))
return false;
var header = new byte[8];
await using var stream = file.OpenReadStream();
var read = await stream.ReadAtLeastAsync(header, header.Length, throwOnEndOfStream: false, ct);
return expected.Any(sig => read >= sig.Length && header.AsSpan(0, sig.Length).SequenceEqual(sig));
}
A signature check does not prove a file is harmless, but it stops renamed executables. Treat it as one layer.
Where should you store uploaded files?
Never use the client's file name for storage. Generate your own, keep the original name only as metadata, and HTML-encode it when you display it:
// Vulnerable: client name, inside wwwroot
var path = Path.Combine(_env.WebRootPath, "uploads", file.FileName);
// Fixed: random name, outside the web root, original name kept as metadata
var storedName = $"{Guid.NewGuid():N}{Path.GetExtension(file.FileName).ToLowerInvariant()}";
var path = Path.Combine(_options.UploadRoot, storedName); // e.g. D:\app-data\uploads
await using (var target = File.Create(path))
await file.CopyToAsync(target, ct);
await _db.Documents.AddAsync(new Document
{
StoredName = storedName,
OriginalName = Path.GetFileName(file.FileName), // display only
OwnerId = userId
}, ct);
Better still, store files in a blob service (Azure Blob Storage, Amazon S3) in a private container.
Presigned URLs for large files
For large uploads, let the browser send the file straight to storage with a short-lived, write-only URL (an S3 presigned URL or an Azure SAS). Your API authorizes the request and issues the URL; it never handles the bytes:
// Angular/TypeScript: ask the API for a URL, then upload directly
const { uploadUrl } = await firstValueFrom(
this.http.post<UploadTicket>('/api/documents/upload-url', { fileName: file.name, size: file.size })
);
await fetch(uploadUrl, { method: 'PUT', body: file, headers: { 'x-ms-blob-type': 'BlockBlob' } });
A final call then tells the API to validate the stored object (size, signature, scan) before marking it usable.
Malware scanning and image re-encoding
Scan files before anyone else can download them: Microsoft Defender for Storage offers malware scanning for blob uploads, and ClamAV is a common self-hosted option. Keep new files in a quarantine state until the scan passes.
For images, re-encode them: decode with an image library, resize if needed and save a new file. That drops embedded metadata and most payloads hidden in the original. Do not accept SVG unless you sanitize it, because SVG can contain script.
How to serve uploaded files safely
[HttpGet("documents/{id:guid}")]
public async Task<IActionResult> Download(Guid id, CancellationToken ct)
{
var doc = await _db.Documents.FirstOrDefaultAsync(d => d.Id == id && d.OwnerId == userId, ct);
if (doc is null) return NotFound(); // also covers documents owned by someone else
Response.Headers["X-Content-Type-Options"] = "nosniff";
var stream = System.IO.File.OpenRead(Path.Combine(_options.UploadRoot, doc.StoredName));
// Passing a download name makes ASP.NET Core send Content-Disposition: attachment
return File(stream, doc.ContentType, doc.OriginalName);
}
The ownership check matters as much as the headers: insecure direct object references on downloads are a broken access control finding. We cover that category in our PR security checklist.
Rate limits for upload endpoints
builder.Services.AddRateLimiter(o =>
o.AddFixedWindowLimiter("uploads", l => { l.PermitLimit = 10; l.Window = TimeSpan.FromMinutes(1); }));
app.UseRateLimiter();
[EnableRateLimiting("uploads")]
[HttpPost("documents")]
public async Task<IActionResult> Upload(...) { ... }
Pitfalls
- Trusting
Content-Typeor the extension alone. - Using
IFormFile.FileNamein a path. - Saving to
wwwrootor any folder the web server serves. - Serving files inline from your main domain, which lets HTML or SVG run as your site.
Checklist
- Size limits set in Kestrel/IIS and per endpoint.
- Extension allowlist plus signature check.
- Random storage names; original name stored as metadata and encoded on display.
- Storage outside the web root or in a private blob container, without execute permission.
- Malware scan before release; images re-encoded.
- Downloads check ownership and send
Content-Disposition: attachmentandnosniff. - Rate limiting on upload endpoints.
Key takeaways
- Everything about an upload is attacker-controlled: name, type, size and content.
- Keep files away from the web root and let storage do the heavy lifting.
- Upload validation is one part of input validation end to end.
Sources
- OWASP File Upload Cheat Sheet
- Microsoft Learn: Upload files in ASP.NET Core
- Microsoft Learn: Rate limiting middleware
- Microsoft Learn: Defender for Storage malware scanning
- AWS: Presigned URLs
Need help securing file uploads?
Santhor audits and fixes upload, storage and download flows in existing .NET applications, and we design secure ones from scratch when you are building something new. We are based in Costa Rica and work nearshore with teams in the U.S. and Latin America. Tell us about your project.