基于角色ASP.NET MVC4的页面权限

本文关键字:MVC4 权限 NET ASP 于角色 角色 | 更新日期: 2023-09-27 18:21:20

实现一种机制的最佳方式是什么?在允许用户访问特定页面之前,系统会检查用户角色?此外,为了在页面中启用一些链接/操作,例如,对于具有"超级"角色的用户,他们可能能够删除/编辑数据,而其他人只能看到它?

供您参考,我不使用ASP.NET MVC中的开箱即用的用户管理(用户是在嵌入到webapp的.mdf数据库中创建的),但我已经开发了自己的用户模块(用于验证、注册和删除用户)。

所以。。解决这个问题的最佳做法是什么?

基于角色ASP.NET MVC4的页面权限

您将编写一个自定义ValidationAttribute:http://msdn.microsoft.com/en-AU/library/system.componentmodel.dataannotations.validationattribute.aspx

基本上,您从ValidationAttribute继承,并覆盖IsValid():

public class IsAnAdminAttribute : ValidationAttribute {
    protected override bool IsValid(object obj) {
        if (Membership.UserInRole("admin"))
            return true; // they can access it
        else
            return false; // can't access it
    }
}

然后将其应用于控制器操作:

[HttpGet]
[IsAnAdmin]
public ActionResult MyAction() {
    // only administrators can access this now
}