File uploads look simple from a user’s perspective: select a file and send it to the server. For an application, however, the operation means accepting untrusted input, controlling resource consumption, choosing a safe storage location, and deciding who may retrieve the result. Using IFormFile alone does not create a secure upload system.
A robust design limits files to the business requirements, validates size and content on the server, never uses a client-provided name as the physical storage name, and keeps content in quarantine until it has passed security checks. These controls reduce both malicious-file risk and abuse of memory, disk, and network resources.
Start with a threat model
An upload endpoint must treat the submitted file name, MIME type, extension, and content as untrusted. Browser-side checks are useful for user experience, but an attacker can bypass them by creating an HTTP request directly.
Common risks include:
- Exhausting memory or disk space with oversized or repeated uploads.
- Using path fragments in a file name to target another directory.
- Uploading content whose extension does not match its actual format.
- Triggering vulnerabilities in image, document, archive, or XML parsers.
- Making uploaded content executable or anonymously reachable through the web root.
- Overwriting an existing file or allowing a user to download another user’s file.
Validation should therefore be layered. Microsoft’s ASP.NET Core guidance covers file-size limits, approved extensions, safe generated names, separate storage, and malware scanning as complementary controls rather than alternatives.
Choose buffering or streaming deliberately
For small files, buffered model binding with IFormFile is convenient. As file sizes and concurrent uploads increase, buffering can consume memory and temporary disk space. Streaming processes the multipart content progressively and can make resource usage more predictable for large files.
Streaming does not make a file trustworthy. It only changes how bytes move through the application. Extension, size, content, authorization, and malware checks are still required.
A basic endpoint for small files
[HttpPost("files")]
[RequestSizeLimit(5 * 1024 * 1024)]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file is null || file.Length == 0)
return BadRequest("A file is required.");
var result = await _fileService.StoreAsync(file);
return Ok(result);
}The request-size attribute is only an early guard. The service layer should enforce the same business rule because files may enter through another endpoint, a background process, or an administrative tool.
Do not trust the file name or path
A submitted name can be retained as a display label, but it should not be used to create a physical path. Values such as ../../appsettings.json, unusual Unicode characters, or platform-specific path syntax can produce unsafe or unexpected results.
Generate a collision-resistant storage name inside the application:
var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
var storageName = $"{Guid.NewGuid():N}{extension}";
var safeOriginalName = Path.GetFileName(file.FileName);Path.GetFileName removes path components, but the resulting value is still untrusted data when displayed, logged, or inserted into another output context. Apply the appropriate output encoding. Build storage paths from an application-controlled root directory and the generated name.
Validate extension, media type, and file signature
The Content-Type header is supplied by the client and must not be treated as proof of file type. Use a small allowlist of extensions based on the actual business requirement. A profile-image feature may need only a few image formats; a document workflow may need PDF and DOCX, but not every possible file type.
File signatures, sometimes called magic numbers, can be checked against the first bytes of a file to detect obvious mismatches between the extension and content. This is useful defense in depth, but it does not eliminate parser vulnerabilities. Use maintained libraries and safe, format-specific processing as well.
var allowed = new[] { ".jpg", ".jpeg", ".png", ".pdf" };
var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowed.Contains(extension))
return BadRequest("This file type is not allowed.");
if (file.Length > 5 * 1024 * 1024)
return BadRequest("The file exceeds the size limit.");Prefer an allowlist over a denylist. Accepting every type and trying to block dangerous extensions later creates a larger and less predictable attack surface.
Keep user files outside the web root
Storing user content under wwwroot is usually a poor default. Depending on static-file configuration, files in that directory may be publicly accessible. Private or personal content should be stored outside the web root and delivered through an endpoint that performs authorization.
A simple layout might look like this:
ContentRoot/
data/
quarantine/
approved/
2026/
10/
Consider quarantine and approved storage as separate security zones. Grant the application account only the permissions it needs, and disable execute permissions in the upload location. If possible, keep uploaded content on storage separate from application binaries and operating-system files.
Use quarantine and malware scanning
Do not expose a newly uploaded file immediately. First write it to quarantine. Store metadata such as the file identifier, owner, original name, extension, length, hash, and scan status in a database.
- Authorize the upload request.
- Apply size and basic content checks.
- Write the file under an application-generated name in quarantine.
- Submit it to an antivirus, sandbox, or organizational content-scanning service.
- If approved, move it to the normal storage area; otherwise, deny access and mark the record as rejected.
If scanning is slow or expensive, use a state-based workflow rather than keeping the HTTP request open. Return statuses such as processing, approved, and rejected. This separates scanner capacity from request-processing capacity and makes retries easier to manage.
Design an authorized download endpoint
For private files, expose a file identifier rather than a physical path. The endpoint should first verify that the current user may access the record, then use the trusted storage name from the database to return the file.
[Authorize]
[HttpGet("files/{id:guid}")]
public async Task<IActionResult> Download(Guid id)
{
var file = await _repository.GetAccessibleFileAsync(id, User);
if (file is null)
return NotFound();
return PhysicalFile(file.Path, file.ContentType, file.OriginalName);
}Never pass a client-supplied path directly to PhysicalFile or a similar API. Content type should come from trusted metadata associated with the accepted file, not blindly from the request header. For sensitive files, also review cache behavior and content-disposition headers.
Production checklist
- Does uploading require authentication and authorization?
- Are extension, size, and file-signature checks performed on the server?
- Is the physical name generated by the application?
- Are files stored outside the web root with execution disabled?
- Are quarantine and approved states separated?
- Is antivirus, sandboxing, or suitable content scanning available?
- Does downloading use an identifier and an access check instead of a user-provided path?
- Can rejected uploads be monitored without logging full file contents or sensitive names?
Secure file uploads are not solved by one framework setting. ASP.NET Core provides useful primitives for binding, streaming, storage, and file responses; security comes from combining those primitives with strict validation, isolated storage, scanning, and authorization-aware delivery.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-10.0
- https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
0 Comments