FileMustExistAttribute.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. /// <summary>
  50. /// 双行根验证,会验证格式
  51. /// </summary>
  52. public class TleStrAttribute : ValidationAttribute
  53. {
  54. /// <summary>
  55. ///
  56. /// </summary>
  57. public TleStrAttribute()
  58. {
  59. }
  60. /// <summary>
  61. /// 文件验证
  62. /// </summary>
  63. /// <param name="value"></param>
  64. /// <returns></returns>
  65. /// <exception cref="Exception"></exception>
  66. public override bool IsValid(object value)
  67. {
  68. if (value.GetType() != typeof(string))
  69. {
  70. throw new Exception($"{nameof(TleStrAttribute)}只能用于string类型!");
  71. }
  72. string tleStr = value.ToString();
  73. if (string.IsNullOrWhiteSpace(tleStr))
  74. {
  75. ErrorMessage = "字段 {0} 值不能为空";
  76. return false;
  77. }
  78. if (!tleStr.Contains(";"))
  79. {
  80. ErrorMessage = $"双行根数[{value}]格式错误,(line1和line2用分号拼到一起)";
  81. return false;
  82. }
  83. return true;
  84. }
  85. }
  86. }