在開發中,假如你只對一個角色進行權限處理,你可以這么寫
class ActionAuthAttribute : AuthorizeAttribute { private RoleType _roleType; public ActionAuthAttribute(RoleType role) { _roleType = role; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (BaseController.CurrentUser.RoleId == (int)_roleType ) { return true; } else { return false; } } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { //base.HandleUnauthorizedRequest(filterContext); //filterContext.HttpContext.Response.RedirectToRoute("ErrorPage", new { msg = HttpUtility.UrlEncodeUnicode("你無權訪問此頁面!") }); System.Web.HttpContext.Current.Response.RedirectToRoute("ErrorPage", new { msg = HttpUtility.UrlEncodeUnicode("你無權訪問此頁面!") }); } }
但是當兩個角色都有權限呢?
方法一:你可以重寫構造函數,如下
class ActionAuthAttribute : AuthorizeAttribute { private RoleType _roleType; private RoleType _roleType1; private RoleType _roleType2; public ActionAuthAttribute(RoleType role) { _roleType = role; } public ActionAuthAttribute(RoleType role1, RoleType role2) { _roleType1 = role1; _roleType2 = role2; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (BaseController.CurrentUser.RoleId == (int)_roleType ) { return true; } else if (BaseController.CurrentUser.RoleId == (int)_roleType1 || BaseController.CurrentUser.RoleId == (int)_roleType2) { return true; } else { return false; } } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { //base.HandleUnauthorizedRequest(filterContext); //filterContext.HttpContext.Response.RedirectToRoute("ErrorPage", new { msg = HttpUtility.UrlEncodeUnicode("你無權訪問此頁面!") }); System.Web.HttpContext.Current.Response.RedirectToRoute("ErrorPage", new { msg = HttpUtility.UrlEncodeUnicode("你無權訪問此頁面!") }); } }
方法二:你可以使用
params定義一個變化的數組參數,這樣參數多少就可以隨你了,推薦第二種方法,不然,隨着參數變化,你要一直重寫函數了。。哈哈
[AttributeUsage(AttributeTargets.Method)] class ActionAuthAttribute : AuthorizeAttribute { private RoleType[] _roleType; public ActionAuthAttribute(params RoleType[] role) { _roleType = role; } protected override bool AuthorizeCore(HttpContextBase httpContext) { foreach (var item in _roleType) { if (BaseController.CurrentUser.RoleId == (int)item) { return true; } } return false; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { var routeValue = new RouteValueDictionary { { "Controller", "Etc"}, { "Action", "Oops"}, {"msg", HttpUtility.UrlEncodeUnicode("你無權訪問此頁面!")} }; filterContext.Result = new RedirectToRouteResult(routeValue); }