0

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

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

那么..这个问题的最佳实践是什么?

4

1 回答 1

2

你会写一个自定义:http ValidationAttribute: //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
}
于 2013-07-08T04:15:48.090 回答