偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

MVC下ASP.NET的表單驗證實現(xiàn)

開發(fā) 后端
MVC下實現(xiàn)表單驗證可以使用多種方法。國外已經(jīng)出現(xiàn)了一些Mvc下使用的驗證框架。本文中提供的方法只是眾多方法之一,可以供學習者參考一二。

在Web開發(fā)中,表單提交算是一種很常見的從客戶端獲取數(shù)據(jù)的方式了。然而,用戶的行為永遠都是無法預料的。為此,我們在程序中不得已必須對用戶輸入的數(shù)據(jù)進行嚴格效驗。在WebForm時代我們常用的手段是驗證控件,但是到了Mvc時代,再使用控件變得困難了,因此我們必須找到新的方式來解決這個問題。

在實際使用中,我們可以考慮多種形式來進行這一驗證(注:本文目前只研究服務器端驗證的情況),最直接的方式莫過于對每個表單值手動用C#代碼進行驗證了,比如:

if(!Int32.TryParse(Request.Form[“age”], out age)){
xxxx…
}
If(age < xxx || age > xxx){
xxxx…
}

 

然而正如上面看到的一樣,這種方式枯燥而繁瑣,需要用戶對每個字段都要手動效驗,或許開發(fā)人員的一不小心就會造成系統(tǒng)的漏洞。因此,制造出一個能對這種行為進行自動進行的輪子勢在必行,當然,到本文寫作的時候為止,國外已經(jīng)出現(xiàn)了一些Mvc下使用的驗證框架,然而天下輪子不怕多,我在此厚顏再造出個,只希望不被冠上山寨之名。

該框架的締造源自4MVC團隊的Infancy項目,去年年底開始這個項目的時候,正是mvc框架加入ModelBinder的時候,當時便想到了通過使用ModelBinder來實現(xiàn)一種服務器端自動驗證框架,經(jīng)過多次修改,該框架慢慢實現(xiàn)了我需要的功能,本系列文章將再次回顧該過程,將該框架的一步步的實現(xiàn)過程加以更細致的重現(xiàn)。

下面正式開始框架的開發(fā),首先我們明確下我們的基本需求:

1.該框架針對簡單實體類(POCO)

2.該框架能自動對實體類的屬性進行效驗

3.該實體能被ModelBinder使用

4.能方便或者自動的執(zhí)行該效驗,并取得效驗結(jié)果和信息

為了實現(xiàn)上面的目標,我們首先來確定一些需要使用的技術手段:

1.要能訪問任意POCO的屬性,必然用到反射

2.要能對屬性進行限制,可選擇使用XML或者Attribute,對程序員來說,Attribute遠比XML來的方便和友好,因此選擇Attribute

3.實現(xiàn)實體驗證方法,可能會使用Command模式,也可能不需要

下面開始我們的實踐了,首先我們考慮測試代碼,假設我擁有實體Student,Student擁有屬性Source,要求Source是int類型,且范圍為0-100,那么測試代碼的模式應該如下:

Student student = new Student(){
Source = -1
};
bool validateResult = student.Validate();
Assert.IsFalse(validateResult);

 

也就是說,我們需要在一個驗證方法中對該對象的所有屬性進行驗證,那么我們考慮對系統(tǒng)各部分的構建,首先我們需要一個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, “分數(shù)的范圍必須在{0}和{1}之間.”)]
public int Source{ get; set; }
}


然而,這樣僅僅是個花架子,在默認情況下這個Range沒有起到任何作用,除了程序員看到代碼之后知道了Source有這樣的限制要求,那么,我們需要如何將這個Attribute和驗證結(jié)合起來呢?自然就是反射。

#p#

我們在Student中實現(xiàn)如下方法:

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;
}


那么再回過頭看先前的測試,我們可以發(fā)現(xiàn),測試成功運行了(相關代碼見附帶項目的Leven.Validate01和test項目Validate01Test.cs).

我們在看目前的代碼,現(xiàn)在我們能測試Source,如果我們的Student類中還有一項Age,范圍為6-150呢,那么Student中加上如下代碼:

[Range(6, 150, "學生年齡必須在{0}和{1}之間.")]
public int Age { get; set; }
那么我們的Validate方法是否能正確驗證呢?為了驗證結(jié)果,我們重新編寫測試:

[TestMethod()]
public void ValidateTest() {
Student student = new Student() {
Source = 80,
Age = 0
};
bool validateResult = student.Validate();
Assert.IsFalse(validateResult);
student.
validateResult = student.Validate();
}


執(zhí)行測試,很遺憾,測試無法通過了.我們可以再看看Validate方法,可以發(fā)現(xiàn),其中只對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來實現(xiàn)該功能,該部分代碼如下(參見項目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);
}


執(zhí)行測試,結(jié)果失敗了.查看原因,顯然可以看到,是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;
}


這次的代碼量增加了不少,不過經(jīng)過我們的不懈努力,測試再一次通過了,但是,我們再次回來查看驗證部分的代碼,不難發(fā)現(xiàn)一個問題,每次我們新增了驗證Attribute之后都必須手動在Validate方法中增加響應的代碼,目前我們還只有兩個Attribute,如果一個系統(tǒng)中有20甚至200個Attribute(當然只是打個比方),該方法的長度恐怕將是個恐怖的數(shù)字,這樣的方法勢必無比丑陋。

【編輯推薦】

  1. ASP.Net MVC框架配置與分析
  2. ASP.net中用axWebBrowser中提交表單
  3. MVC詳解 什么是真正的"框架"
責任編輯:yangsai 來源: ITPUB論壇
相關推薦

2009-07-29 16:47:40

ASP.NET表單身份

2009-07-20 15:44:32

ASP.NET MVC

2014-04-09 10:18:21

ASP.NETMVC

2009-09-18 10:20:26

PRG數(shù)據(jù)驗證

2009-07-28 14:47:18

ASP.NET MVC

2011-04-12 13:53:25

ASP.NET MVCjQuery

2009-07-29 17:23:17

ASP.NET表單

2009-07-24 13:20:44

MVC框架ASP.NET

2009-07-31 12:43:59

ASP.NET MVC

2009-09-10 09:50:47

ASP.NET MVC

2009-07-23 16:59:31

ASP.NET認證Form表單

2009-06-01 10:23:31

asp.net mvcasp.net mvc.net mvc框架

2009-07-22 16:02:39

ASP.NET MVCPagedList

2009-07-29 09:59:10

ASP.NET For

2009-07-22 18:07:55

論壇應用程序ASP.NET MVC

2009-11-24 15:11:21

ASP.NET MVC

2009-07-22 10:34:37

ActionInvokASP.NET MVC

2009-07-22 09:11:02

Action方法ASP.NET MVC

2009-08-05 18:22:55

2009-07-22 13:24:24

ASP.NET MVC
點贊
收藏

51CTO技術棧公眾號