Validation on IEnumerable not applied - ASP.Net Core Web APIs

43 Views Asked by At

I have an endpoint that accepts more than one media uploading while sending a List of DTOs no validation applies, validation only work on a single DTO.

Here is the DTO that endpoint accept as a payload:

public class MediaDto
{
    [Required]
    [DataType(DataType.Upload)]
    [MaxFileSize(20 * 1024 * 1024)]
    [AllowedExtensions(new[] { ".jpg", ".png", ".jpeg", ".tiff", ".raw", ".webm", ".ogg", ".m4v", ".mp4" })]
    public IFormFile File { get; set; }
    [Required] public int Width { get; set; }
    [Required] public int Height { get; set; }
}

The Controller Action

public IActionResult AddMedia([FromForm][Required] IEnumerable<MediaDto> media)
{
   return Ok(_momentService.AddMedia(media));
}

Validation Not Applied to the above case

If I change the controller action to accept only one object the validation will applied

public IActionResult AddMedia([FromForm] MediaDto media)
{
  return Ok(_momentService.AddMedia(media));
}

Custom Validation Attribute

public class AllowedExtensionsAttribute : ValidationAttribute
{
    private readonly string[] _extensions;

    /// <inheritdoc />
    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }

    /// <inheritdoc />
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value is not IFormFile file) return new ValidationResult(GetErrorMessage());
        var extension = Path.GetExtension(file.FileName);
        return !_extensions.Contains(extension.ToLower()) ? new ValidationResult(GetErrorMessage()) : ValidationResult.Success;
    }

    private static string GetErrorMessage()
    {
        return $"This photo extension is not allowed!";
    }
}

enter image description here

0

There are 0 best solutions below