發表文章

目前顯示的是 10月, 2010的文章

[MVC學習心得]如何自訂Authorize

在MVC的 Action方法可以冠上Authorize的Attribute,並可以指定授權角色,來驗證使用者是否有權限執行 如:[Authorize(Roles="Admin")] 但若要動態指定Roles時, 則 會出現訊息 "錯誤 2 屬性引數必須是常數運算式、typeof 運算式或屬性參數型別的陣列建立運算式 " 程式如下: [Authorize(Roles=staticClass.GetCurrentRole())] Ps: staticClass.GetCurrentRole()),此方法是在依照DB的資料來指定權限 。   若想依照 DB 的資料來判斷權限,可以參考如下 1.新增一類別並繼承AuthorizeAttribute 並新增一自訂屬性PrgNo public class MyCustomAuthorizeAttribute : AuthorizeAttribute   /// <summary> /// 程式編號 /// </summary> public string PrgNo { get; set; } } 2.覆寫AuthorizeCore方法 protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null ) throw new ArgumentNullException( "httpContext" ); string [] users = Users.Split( ',' ); if (!httpContext.User.Identity.IsAuthenticated) return false ; //取得使用者的角色 FormsIdentity id = httpContext.Us