AllowedExtensionsAttribute.cs 1.7 KB

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