在开发中,假如你只对一个角色进行权限处理,你可以这么写
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); }
时间: 2024-10-07 18:26:21