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
Prevents denial-of-service attacks
Protects server memory and performance
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
Prevent upload of malicious executable files
Ensures only expected formats reach your server
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
Prevents overwriting existing files
Avoids user-controlled file paths
Join the conversation! Your thoughts help the community grow.