using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MalwareMultiScan.Api.Attributes
{
///
/// Validate uploaded file size for the max file size defined in settings.
///
public class MaxFileSizeAttribute : ValidationAttribute
{
///
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var maxSize = validationContext
.GetRequiredService()
.GetValue("MaxFileSize");
var formFile = (IFormFile) value;
if (formFile == null || formFile.Length > maxSize)
return new ValidationResult($"File exceeds the maximum size of {maxSize} bytes");
return ValidationResult.Success;
}
}
}