在Web開發中,表單提交算是一種很常見的從客戶端獲取數據的方式了。然而,用戶的行為永遠都是無法預料的。為此,我們在程序中不得已必須對用戶輸入的數據進行嚴格效驗。在WebForm時代我們常用的手段是驗證控件,但是到了Mvc時代,再使用控件變得困難了,因此我們必須找到新的方式來解決這個問題。
在實際使用中,我們可以考慮多種形式來進行這一驗證(注:本文目前只研究服務器端驗證的情況),最直接的方式莫過于對每個表單值手動用C#代碼進行驗證了,比如:
if(!Int32.TryParse(Request.Form[“age”], out age)){ xxxx… } If(age < xxx || age > xxx){ xxxx… }
|
然而正如上面看到的一樣,這種方式枯燥而繁瑣,需要用戶對每個字段都要手動效驗,或許開發人員的一不小心就會造成系統的漏洞。因此,制造出一個能對這種行為進行自動進行的輪子勢在必行,當然,到本文寫作的時候為止,國外已經出現了一些Mvc下使用的驗證框架,然而天下輪子不怕多,我在此厚顏再造出個,只希望不被冠上山寨之名。
該框架的締造源自4MVC團隊的Infancy項目,去年年底開始這個項目的時候,正是mvc框架加入ModelBinder的時候,當時便想到了通過使用ModelBinder來實現一種服務器端自動驗證框架,經過多次修改,該框架慢慢實現了我需要的功能,本系列文章將再次回顧該過程,將該框架的一步步的實現過程加以更細致的重現。
下面正式開始框架的開發,首先我們明確下我們的基本需求:
1.該框架針對簡單實體類(POCO)
2.該框架能自動對實體類的屬性進行效驗
3.該實體能被ModelBinder使用
4.能方便或者自動的執行該效驗,并取得效驗結果和信息
為了實現上面的目標,我們首先來確定一些需要使用的技術手段:
1.要能訪問任意POCO的屬性,必然用到反射
2.要能對屬性進行限制,可選擇使用XML或者Attribute,對程序員來說,Attribute遠比XML來的方便和友好,因此選擇Attribute
3.實現實體驗證方法,可能會使用Command模式,也可能不需要
下面開始我們的實踐了,首先我們考慮測試代碼,假設我擁有實體Student,Student擁有屬性Source,要求Source是int類型,且范圍為0-100,那么測試代碼的模式應該如下:
Student student = new Student(){ Source = -1 }; bool validateResult = student.Validate(); Assert.IsFalse(validateResult);
|
也就是說,我們需要在一個驗證方法中對該對象的所有屬性進行驗證,那么我們考慮對系統各部分的構建,首先我們需要一個RangeAttribute,這個類能包含對屬性的驗證信息,大致如下:
public class RangeAttribute : Attribute{ public int Mix{ get; set; } //范圍下限 public int Max{ get; set; } //范圍上限 public string Message{ get; set;} //出錯信息
public RangeAttribute(int min, int max, string message){ Min = min; Max = max; Message = message; } }
|
這樣一來我們的Student就可以如此構造
public class Student{ [Range(0, 100, “分數的范圍必須在{0}和{1}之間.”)] public int Source{ get; set; } }
|
然而,這樣僅僅是個花架子,在默認情況下這個Range沒有起到任何作用,除了程序員看到代碼之后知道了Source有這樣的限制要求,那么,我們需要如何將這個Attribute和驗證結合起來呢?自然就是反射。
#p#
我們在Student中實現如下方法:
public bool Validate(){ bool result = true; Type type = this.GetType(); PropertyInfo property = type.GetProperty(“Source”); //獲取Source屬性 RangeAttribute [] attributes = property.GetCustomAttributes(typeof(Attribute), true) as RangeAttribute []; //獲取Range屬性集合 //遍歷集合對屬性進行驗證 foreach(var item in attribute){ int value = (int)property.GetValue(this, null); if(value < item.Min || value > item.Max){ result = false; } } return result; }
|
那么再回過頭看先前的測試,我們可以發現,測試成功運行了(相關代碼見附帶項目的Leven.Validate01和test項目Validate01Test.cs).
我們在看目前的代碼,現在我們能測試Source,如果我們的Student類中還有一項Age,范圍為6-150呢,那么Student中加上如下代碼:
[Range(6, 150, "學生年齡必須在{0}和{1}之間.")] public int Age { get; set; } 那么我們的Validate方法是否能正確驗證呢?為了驗證結果,我們重新編寫測試:
[TestMethod()] public void ValidateTest() { Student student = new Student() { Source = 80, Age = 0 }; bool validateResult = student.Validate(); Assert.IsFalse(validateResult); student. validateResult = student.Validate(); }
|
執行測試,很遺憾,測試無法通過了.我們可以再看看Validate方法,可以發現,其中只對Source屬性進行了驗證,那么我們可以想辦法修改代碼,讓其能對Age和Source方法同時驗證。
public bool Validate() { bool result = true; Type type = this.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (var property in properties) { RangeAttribute[] attributes = property.GetCustomAttributes(typeof(RangeAttribute), true) as RangeAttribute[]; foreach (var item in attributes) { int value = (int)property.GetValue(this, null); if (value < item.Min || value > item.Max) { result = false; } } } return result; }
|
修改過的方法中將遍歷所有的屬性,然后進行驗證,這時候再次運行測試,生動的綠色代表我們重新獲得了成功。
下面我們再次考慮新的可能情況,如果Student需要一個Name屬性,這是一個必須字段.我們考慮新增一個RequiredAttribute來實現該功能,該部分代碼如下(參見項目Leven.Validate03):
[AttributeUsage(AttributeTargets.Property)] public class RequiredAttribute : Attribute { public bool IsRequired { get; set; } public string Message { get; set; } public RequiredAttribute(string message) { IsRequired = true; Message = message; } }
|
然后修改Student部分,新增下面部分:
[Required] public string Name { get; set; } 再次修改測試代碼:
[TestMethod()] public void ValidateTest() { Student student = new Student() { Age = 20, Source = 89, Name = string.Empty }; bool validateResult = student.Validate(); Assert.IsFalse(validateResult); }
|
執行測試,結果失敗了.查看原因,顯然可以看到,是Validate方法中
RangeAttribute[] attributes =property.GetCustomAttributes(typeof(RangeAttribute), true) as RangeAttribute[];
只驗證了RangeAttribute,那針對我們加入的RequiredAttribute自然是無能為力了,為了能驗證RequiredAttribute,我們再次修改了代碼:
public bool Validate() { bool result = true; bool requiredResult = true; Type type = this.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (var property in properties) { RangeAttribute[] attributes = property.GetCustomAttributes(typeof(RangeAttribute), true) as RangeAttribute[]; //獲取RangeAttribute集合 RequiredAttribute[] requiredAttributes = property.GetCustomAttributes(typeof(RequiredAttribute), true) as RequiredAttribute[]; //獲取RequiredAttribute集合 //遍歷RangeAttribute進行驗證 foreach (var item in attributes) { int value = (int)property.GetValue(this, null); if (value < item.Min || value > item.Max) { result = false; } } //遍歷RequiredAttr進行驗證 foreach (var item in requiredAttributes) { object value = property.GetValue(this, null); if (value is string) { if (String.IsNullOrEmpty((value as string))) { requiredResult = false; } } else { if (value == null) { requiredResult = false; } } } } return result && requiredResult; }
|
這次的代碼量增加了不少,不過經過我們的不懈努力,測試再一次通過了,但是,我們再次回來查看驗證部分的代碼,不難發現一個問題,每次我們新增了驗證Attribute之后都必須手動在Validate方法中增加響應的代碼,目前我們還只有兩個Attribute,如果一個系統中有20甚至200個Attribute(當然只是打個比方),該方法的長度恐怕將是個恐怖的數字,這樣的方法勢必無比丑陋。
【編輯推薦】
- ASP.Net MVC框架配置與分析
- ASP.net中用axWebBrowser中提交表單
- MVC詳解 什么是真正的"框架"