我正在尝试实现角色授权机制,该机制检查当前登录用户的角色,如果用户处于正确的角色,他/她被允许,否则显示错误视图.
问题是当用户尝试访问控制器中的以下方法时,他确实进入了RoleAuthorizationAttribute类并获得验证,但是控制器中的方法未被执行.
注意:用户具有客户角色
控制器方法
[RoleAuthorization(Roles = "Client,Adminsitrator")] public ActionResult addToCart(int ProductID,string Quantity) { tempShoppingCart t = new tempShoppingCart(); t.ProductID = ProductID; t.Username = User.Identity.Name; t.Quantity = Convert.ToInt16(Quantity); new OrdeRSService.OrdersClient().addToCart(t); ViewData["numberOfItemsInShoppingCart"] = new OrdeRSService.OrdersClient().getNoOfItemsInShoppingCart(User.Identity.Name); ViewData["totalPriceInSC"] = new OrdeRSService.OrdersClient().getTotalPriceOfItemsInSC(User.Identity.Name); return PartialView("quickShoppingCart","Orders"); }
角色验证类
[System.AttributeUsage(System.AttributeTargets.All,AllowMultiple = false,Inherited = true)] public sealed class RoleAuthorizationAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { List<String> requiredRoles = Roles.Split(Convert.tochar(",")).ToList(); List<Role> allRoles = new UseRSService.UsersClient().GetUserRoles(filterContext.HttpContext.User.Identity.Name).ToList(); bool Match = false; foreach (String s in requiredRoles) { foreach (Role r in allRoles) { string rName = r.RoleName.Trim().ToString(); string sName = s.Trim(); if (rName == sName) { Match = true; } } } if (!Match) { filterContext.Result = new ViewResult { ViewName = "AccessDenied" }; } base.OnAuthorization(filterContext); } }
你能告诉我我做错了什么
解决方法
由于我有数据库中的用户的角色,所以我必须检查数据库,所以我将这个方法包含在global.asax中
protected void Application_AuthenticateRequest(object sender,EventArgs args) { if (Context.User != null) { IEnumerable<Role> roles = new UseRSService.UsersClient().GetUserRoles( Context.User.Identity.Name); string[] rolesArray = new string[roles.Count()]; for (int i = 0; i < roles.Count(); i++) { rolesArray[i] = roles.ElementAt(i).RoleName; } GenericPrincipal gp = new GenericPrincipal(Context.User.Identity,rolesArray); Context.User = gp; } }
然后我可以使用正常
[Authorize(Roles = "Client,Administrator")]
在控制器中的actionResult方法之上
这工作.