你是否需要對一個頁面進行登陸或其它權限的驗證,你的作法是怎樣的,可能在以前的程序開發中,會使用
if .... else 這樣的條件判斷,遍布在你的程序代碼中,而對於.net的程序員來說,有一個福音,那不是Attribute,即"特性"
它的出現,改變了代碼設計方式,你再也不需要到處都有的if else了,你只要把它寫在一個自定義的Attribute里就可以了,其實.這也是net比其它更友好,更對程序員有吸引力的原因,也是我信仰它的原因.
過去的程序:在一個需要登陸的頁面可能你要寫成這樣
1 if (string.IsNullOrEmpty(session("userid"))) 2 3 response.redirect("/account/logon.aspx");
現在的程序:
1 [UserAuthentication(AuthenticationType.BackgroundLogin)] 2 public partial class SystemController : BackgroundBaseController 3 { 4 5 // ... 6 7 }
這樣,這個類下面的所有方法對應的頁面都將進行登陸的驗證,是否是很神奇,呵呵.
以下是用戶驗證特性的完整代碼,供大家參考
1 /// <summary> 2 /// 用戶驗證列舉 3 /// </summary> 4 public enum AuthenticationType 5 { 6 /// <summary> 7 /// 登錄 8 /// </summary> 9 Login, 10 /// <summary> 11 /// 后台登陸 12 /// </summary> 13 BackgroundLogin, 14 /// <summary> 15 /// 注冊 16 /// </summary> 17 Register, 18 } 19 20 /// <summary> 21 /// 用戶驗證過濾器:前台 22 /// </summary> 23 public class UserAuthentication : AuthorizeAttribute 24 { 25 public AuthenticationType Authentication { get; set; } 26 /// <summary> 27 /// 構造函數 28 /// </summary> 29 public UserAuthentication() 30 : this(AuthenticationType.Login) { } 31 public UserAuthentication(AuthenticationType authentication) 32 { 33 this.Authentication = authentication; 34 } 35 /// <summary> 36 /// 執行前驗證 37 /// </summary> 38 public override void OnAuthorization(AuthorizationContext filterContext) 39 { 40 41 //驗證不成功的時候 42 switch (this.Authentication) 43 { 44 case AuthenticationType.Login: 45 if (!ClientHelper.Current.HasUserInfo) 46 filterContext.Result = new RedirectResult 47 ("/Account/LogOn?returnUrl=" + HttpContext.Current.Request.Url.ToString()); 48 break; 49 50 case AuthenticationType.BackgroundLogin: 51 if (string.IsNullOrEmpty(SessionAction.ReadSession("Background_Current_UserID")) || Convert.ToInt32(SessionAction.ReadSession("Background_Current_UserID")) < 0) 52 filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "LogOn" }, { "Controller", "Account" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } }); 53 break; 54 case AuthenticationType.Register: 55 filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Register" }, { "Controller", "Account" } }); 56 break; 57 default: 58 filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Index" }, { "Controller", "Home" } }); 59 break; 60 } 61 62 } 63 }
大家請注意一個地方RouteValueDictionary這個類型,可以建立一個字典對象,將你的action和controller寫進去就可以組成一個完成的URL,是方法RedirectToRouteResult的作用是叫程序跳到指定的路由中去,你的路由中可以是以SHTML為擴展名,也可以是ASPX,再或者HTML都可以自動選擇的.呵呵.