using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XdCxRhDW.Dto.Attribute { /// /// 文件存在性验证,会验证本地文件是否存在 /// public class FileMustExistAttribute : ValidationAttribute { /// /// /// public FileMustExistAttribute() { } /// /// 文件验证 /// /// /// /// public override bool IsValid(object value) { if (value.GetType() != typeof(string)) { throw new Exception($"{nameof(FileMustExistAttribute)}只能用于string类型!"); } string fileName = value.ToString(); if(string.IsNullOrWhiteSpace(fileName) ) { ErrorMessage= "字段 {0} 值不能为空"; return false; } if (fileName.Contains("\\") || fileName.Contains("/")) { ErrorMessage = $"文件[{value}]格式错误,必须是上传后返回的名称"; return false; } ErrorMessage = $"文件[{value}]不存在,请先上传"; string localFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", fileName); return File.Exists(localFile); } } /// /// 双行根验证,会验证格式 /// public class TleStrAttribute : ValidationAttribute { /// /// /// public TleStrAttribute() { } /// /// 文件验证 /// /// /// /// public override bool IsValid(object value) { if (value.GetType() != typeof(string)) { throw new Exception($"{nameof(TleStrAttribute)}只能用于string类型!"); } string tleStr = value.ToString(); if (string.IsNullOrWhiteSpace(tleStr)) { ErrorMessage = "字段 {0} 值不能为空"; return false; } if (!tleStr.Contains(";")) { ErrorMessage = $"双行根数[{value}]格式错误,(line1和line2用分号拼到一起)"; return false; } return true; } } }