標籤:
概述
在把使用者輸入的資料存放區到資料庫之前一般都要對資料做服務端校正,於是想到了.net內建的資料校正架構validator。本文對validator的使用方法進行介紹,並分析下校正的的原理。
使用validator校正資料
首先我們建立一個需要校正的實體類代碼如下:
[Table("apple")] public class Apple { public Guid Id {get;set;} [MaxLength(3,ErrorMessage="名稱長度不能超過3個")] public string Name {get;set;} public string Comment {get;set;} public virtual ICollection<Banana> Bananas { get; set; } }
我們在Name屬性添加了一個校正中繼資料MaxLength。
然後使用下面的代碼對資料進行校正:
Apple apple = new Apple(){Name = "tes你"};
string strLength = "";
List<ValidationResult> results = new List<ValidationResult>(); ValidationContext validateContext = new ValidationContext(apple); if (Validator.TryValidateObject(apple, validateContext, results, true)) { strLength = "it is ok!"; }
校正失敗會在 results中出現錯誤資訊。
自訂校正方法
例如上面的例子,如果我們希望是按位元組數來校正資料,而不是字串長度。我們就需要對校正方法進行擴張並自訂實現校正方法了。擴充校正方法的代碼如下:
public class NewMaxLengthAttribute : MaxLengthAttribute { public NewMaxLengthAttribute() : base() { } public NewMaxLengthAttribute(int length) : base(length) { } public override bool IsValid(object value) { if (value != null && value is string ) { int byteLength = System.Text.Encoding.Default.GetByteCount(value.ToString()); if ( byteLength > base.Length ) { return false; } } return true; } }
對MaxLengthAttribute進行繼承,並重載校正方法IsValid即可。
validator實現原理分析
類比validator代碼如下:
Apple apple = new Apple(){Name = "tes你"};
Type typeForTest = apple.GetType(); foreach (PropertyInfo ai in typeForTest.GetProperties()) { var test = ai.GetCustomAttribute(typeof(MaxLengthAttribute), false) as MaxLengthAttribute; var aiType = ai.GetType(); if (test != null && ai.PropertyType.Name.Equals("String")) { var length = test.Length; var propertyValue = ai.GetValue(apple).ToString(); int byteLength = System.Text.Encoding.Default.GetByteCount(propertyValue); if (length >= byteLength) { res+= " OK"; } else {
res+= "資料不合理";
}
}
}
利用反射讀取實體的屬性上定義的中繼資料資訊,然後對資料進行校正。
.net 使用validator做資料校正