Introduction
Handling file uploads is a common requirement in many applications—profile images, documents, reports, media files, and more. But accepting user files also introduces security risks. Attackers may upload harmful scripts, oversized files, or disguised malware. That’s why secure file upload handling is critical when building a .NET Web API. In this article, we will walk through the correct and safe way to implement file uploads in .NET Web API using clear and beginner-friendly language.
Use IFormFile to Receive the Uploaded File
The simplest way to handle uploads in .NET Web API is using IFormFile.
Example Endpoint
[HttpPost("upload")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded");
return Ok("File received successfully");
}
Why This Works
Accepts uploaded files in multipart/form-data
Easy to validate and inspect
Works for images, documents, and media files
Apply File Size Limits to Prevent Abuse
Attackers may try to upload extremely large files to crash your server.
Set File Size Limit in Controller
if (file.Length > 5 * 1024 * 1024) // 5 MB
return BadRequest("File is too large");
Configure Max Allowed Request Body in Program.cs
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10 MB
});
Why It Matters
Validate File Extensions and MIME Types
Attackers may upload .exe or .js files disguised as images.
Validate Extension
var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".pdf" };
var extension = Path.GetExtension(file.FileName).ToLower();
if (!allowedExtensions.Contains(extension))
return BadRequest("Invalid file type");
Validate MIME Type
if (!file.ContentType.StartsWith("image") && file.ContentType != "application/pdf")
return BadRequest("Invalid content type");
Why Validation Is Necessary
Generate a Safe File Name
Never use the original file name directly to avoid path traversal attacks.
Secure Name Generation
var safeFileName = Guid.NewGuid().ToString() + extension;
Why This Helps
Store Files Outside the Web Root (Important!)
Never store uploaded files in the /wwwroot folder.
Secure Directory
/app_data/uploads/
Example Save Code
var filePath = Path.Combine(_env.ContentRootPath, "Uploads", safeFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
Why Store Outside Web Root?
Use Streaming for Very Large Files
IFormFile loads the file into memory. For large files, use streaming.
Example
[RequestSizeLimit(50_000_000)] // 50 MB
[HttpPost("stream-upload")]
public async Task<IActionResult> UploadLargeFile()
{
var boundary = MultipartRequestHelper.GetBoundary(
MediaTypeHeaderValue.Parse(Request.ContentType),
50_000_000);
// Stream logic here
return Ok();
}
Why Streaming?
Scan Uploaded Files for Malware (Highly Recommended)
Use an antivirus engine like ClamAV, Windows Defender API, or third-party virus scanners.
Example (ClamAV)
var clam = new ClamClient("localhost", 3310);
var result = await clam.ScanFileOnServerAsync(filePath);
if (result.Result == ClamScanResults.VirusDetected)
{
System.IO.File.Delete(filePath);
return BadRequest("Malicious file detected");
}
Why Scan Uploaded Files?
Restrict Who Can Upload Files
Use authentication and authorization.
Example
[Authorize]
[HttpPost("upload-secure")]
public IActionResult UploadSecure(IFormFile file) {...}
Why?
Log Every Upload Request
Logging helps in auditing and tracing suspicious activity.
Example
_logger.LogInformation("File uploaded: {FileName}, Size: {Size}", file.FileName, file.Length);
Why Logging Helps
Use HTTPS for Secure File Transfer
Always use HTTPS when uploading files.
Benefits
Best Practices for Secure File Uploads in .NET Web API
Validate file type and MIME type
Limit file size at multiple levels
Generate safe file names
Store uploads outside web root
Scan files for viruses
Use HTTPS for all uploads
Avoid using user input in file paths
Log all upload attempts
Use streaming for large files
Always secure upload endpoints with authentication
Conclusion
Secure file upload handling is essential for protecting your .NET Web API from potential attacks. By validating file types, restricting sizes, sanitizing file names, scanning for malware, and storing files safely, you greatly reduce security risks. Implementing these best practices ensures your application stays fast, secure, and reliable. With the right approach, you can confidently accept file uploads while keeping your system and users safe.