Custom File Size Validation Attribute in ASP.NET Core
Sandeep Pal
9+ Exp | C# | Dotnet Core | Web API | MVC 5 | Azure | React Js | Node JS | Microservices | Sql | MySQL | JavaScript | UnitTest | Dapper | Linq | DSA | Entity framework Core | Web Forms | Jquery | MongoDB | Quick Learner
Custom File Size Validation Attribute in ASP.NET Core
When developing web applications in ASP.NET Core, handling file uploads efficiently and validating their sizes is a common requirement. To address this, you can create a custom validation attribute that ensures uploaded files do not exceed a specified size limit. Below is an overview of how to implement such a custom attribute using MaxFileSizeAttribute.
Overview
The MaxFileSizeAttribute class is a custom validation attribute designed to validate file sizes. It extends the ValidationAttribute class from the System.ComponentModel.DataAnnotations namespace and provides functionality to enforce file size constraints.
Implementation
Here's a step-by-step breakdown of the MaxFileSizeAttribute implementation:
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
2. Validation Logic: The IsValid method overrides the base ValidationAttribute class’s IsValid method. This method performs the actual validation. It checks if the value is of type IFormFile, which represents the uploaded file. If the file's size exceeds the maximum allowed size, it returns a ValidationResult with an appropriate error message.
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
var file = value as IFormFile; if (file != null)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
3. Error Message: The GetErrorMessage method provides a default error message indicating the maximum allowed file size. This message can be customized to make it more user-friendly if needed
Complete Code:
public class MaxFileSizeAttribute:ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
var file = value as IFormFile;
if (file != null)
{
if(file.Length>_maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Maximum allowed file size is {_maxFileSize} bytes.";
}