dri*_*u16 13 asp.net-mvc authorization asp.net-mvc-3
我正在尝试实现角色授权机制,该机制检查当前登录用户的角色,如果用户处于正确的角色,则允许他/她,否则显示错误视图.
问题是,当用户尝试访问控制器中的下面方法时,他确实进入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");
}
Run Code Online (Sandbox Code Playgroud)
角色身份验证类
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我我做错了吗?
dri*_*u16 16
由于我在数据库中拥有用户的角色,因此我必须检查数据库,因此我将此方法包含在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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以使用正常
[Authorize(Roles = "Client, Administrator")]
Run Code Online (Sandbox Code Playgroud)
在控制器中的actionResult方法之上
这很有效.
| 归档时间: |
|
| 查看次数: |
54847 次 |
| 最近记录: |