In this lesson, you will learn how to securely accept user-uploaded files using Razor Pages and the IFormFile interface.
The Razor Form Setup
To upload files, your Razor form must be configured to handle binary data. The standard form encoding is insufficient; you must set the enctype attribute to multipart/form-data. Without this, the browser will not send the file contents as part of the request body.
<form method="post" enctype="multipart/form-data">
<input type="file" name="userFile" />
<button type="submit">Upload</button>
</form>
Server-Side Ingestion
In your PageModel, you use the IFormFile type to capture the incoming data. When the request hits the handler, the ModelBinder automatically populates the IFormFile property with the file's metadata and a stream to its content.
public class UploadModel : PageModel
{
[BindProperty]
public IFormFile UserFile { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (UserFile != null && UserFile.Length > 0)
{
var filePath = Path.Combine("wwwroot/uploads", UserFile.FileName);
using (var stream = System.IO.File.Create(filePath))
{
await UserFile.CopyToAsync(stream);
}
}
return Page();
}
}
Essential Security Considerations
When handling file uploads, you must never trust user-supplied metadata. Implementing these practices is vital for secure ingestion:
- Limit File Size: Use the
[RequestSizeLimit]or[RequestFormLimits]attributes to prevent DoS attacks via massive file uploads. - Validate Extensions: Do not rely on the
FileNameproperty alone. Verify the file extension against a whitelist of allowed types (e.g.,.jpg,.pdf). - Rename Files: Never save a file using the user’s original filename, as this invites path traversal vulnerabilities. Generate a unique
Guidor internal identifier instead. - Storage Location: Always store uploaded files outside of the application's root directory or in a dedicated storage service to prevent users from executing scripts they have uploaded.
Key Takeaway: Always use multipart/form-data for your forms and treat every incoming IFormFile as malicious by validating its size, type, and path before writing it to your server.