查看我的原始答案
https://stackoverflow.com/a/12603828/1171321
基本上结合我在博客文章中的方法和TryValidateProperty()建议来维护模型验证注释。
编辑:
我继续在博客文章中对我的代码进行了代码增强。我很快就会发布这个更新的代码。下面是一个简单的示例,它验证每个属性并允许您访问结果数组。只是一种方法的示例
public class FileUpload<T>
{
private readonly string _RawValue;
public T Value { get; set; }
public string FileName { get; set; }
public string MediaType { get; set; }
public byte[] Buffer { get; set; }
public List<ValidationResult> ValidationResults = new List<ValidationResult>();
public FileUpload(byte[] buffer, string mediaType, string fileName, string value)
{
Buffer = buffer;
MediaType = mediaType;
FileName = fileName.Replace("\"","");
_RawValue = value;
Value = JsonConvert.DeserializeObject<T>(_RawValue);
foreach (PropertyInfo Property in Value.GetType().GetProperties())
{
var Results = new List<ValidationResult>();
Validator.TryValidateProperty(Property.GetValue(Value),
new ValidationContext(Value) {MemberName = Property.Name}, Results);
ValidationResults.AddRange(Results);
}
}
public void Save(string path, int userId)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var SafeFileName = Md5Hash.GetSaltedFileName(userId,FileName);
var NewPath = Path.Combine(path, SafeFileName);
if (File.Exists(NewPath))
{
File.Delete(NewPath);
}
File.WriteAllBytes(NewPath, Buffer);
var Property = Value.GetType().GetProperty("FileName");
Property.SetValue(Value, SafeFileName, null);
}
}