AllowedExtensionsAttribute.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Microsoft.AspNetCore.Http;
  2. using System.Collections;
  3. using System.ComponentModel.DataAnnotations;
  4. namespace SharedKernel.Attributes;
  5. /*
  6. * 파일 확장자 제한
  7. */
  8. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
  9. public class AllowedExtensionsAttribute : ValidationAttribute
  10. {
  11. private readonly string[] _extensions;
  12. public AllowedExtensionsAttribute(string extensions)
  13. {
  14. _extensions = extensions.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(x => x.Trim().TrimStart('.').ToLowerInvariant()).Where(x => x.Length > 0).ToArray();
  15. }
  16. public override bool IsValid(object? value)
  17. {
  18. if (value is IFormFile file)
  19. {
  20. return _checkExtension(file.FileName);
  21. }
  22. if (value is IEnumerable files)
  23. {
  24. foreach (var obj in files)
  25. {
  26. if (obj is IFormFile f && !_checkExtension(f.FileName))
  27. {
  28. return false;
  29. }
  30. }
  31. }
  32. return true;
  33. }
  34. public override string FormatErrorMessage(string name)
  35. {
  36. var template = string.IsNullOrWhiteSpace(ErrorMessage) ? "{0}에 허용되지 않은 파일 형식이 있습니다.\n\n허용 확장자: [{1}]" : ErrorMessage;
  37. return string.Format(template, name, string.Join(", ", _extensions));
  38. }
  39. private bool _checkExtension(string fileName)
  40. {
  41. var ext = Path.GetExtension(fileName)?.TrimStart('.').ToLowerInvariant();
  42. return !string.IsNullOrEmpty(ext) && _extensions.Contains(ext);
  43. }
  44. }