FileMustExistAttribute.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace XdCxRhDw.Dto.Attribute
  9. {
  10. /// <summary>
  11. /// 文件存在性验证,会验证本地文件是否存在
  12. /// </summary>
  13. public class FileMustExistAttribute : ValidationAttribute
  14. {
  15. /// <summary>
  16. ///
  17. /// </summary>
  18. public FileMustExistAttribute()
  19. {
  20. }
  21. /// <summary>
  22. /// 文件验证
  23. /// </summary>
  24. /// <param name="value"></param>
  25. /// <returns></returns>
  26. /// <exception cref="Exception"></exception>
  27. public override bool IsValid(object value)
  28. {
  29. if (value.GetType() != typeof(string))
  30. {
  31. throw new Exception($"{nameof(FileMustExistAttribute)}只能用于string类型!");
  32. }
  33. string fileName = value.ToString();
  34. if(string.IsNullOrWhiteSpace(fileName) )
  35. {
  36. ErrorMessage= "字段 {0} 值不能为空";
  37. return false;
  38. }
  39. if (fileName.Contains("\\") || fileName.Contains("/"))
  40. {
  41. ErrorMessage = $"文件[{value}]格式错误,必须是上传后返回的名称";
  42. return false;
  43. }
  44. ErrorMessage = $"文件[{value}]不存在,请先上传";
  45. string localFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", fileName);
  46. return File.Exists(localFile);
  47. }
  48. }
  49. }