Custom File Size Validation Attribute in ASP.NET Core

Custom File Size Validation Attribute in ASP.NET Core

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:

  1. Constructor: The constructor accepts an integer parameter, maxFileSize, which defines the maximum allowed file size in bytes.

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.";
        }        

#webdevelopment hashtag#softwareengineer hashtag#softwaredevelopment hashtag#softwaredevelopmentlifecycle hashtag#softwaredevelopmentfullcoursehashtag#programming hashtag#dotnet hashtag#asp.netcore hashtag#csharp

要查看或添加评论,请登录

Sandeep Pal的更多文章

社区洞察

其他会员也浏览了