简体   繁体   English

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

[英]Page Permission based on Role ASP.NET MVC4

What is the best way of implementing a mechanism where the system check the user role before permitting it to access some specific page? 在允许系统访问某个特定页面之前,系统检查用户角色的机制的最佳实现方式是什么? Also to enable maybe some link/action in the page, for example for users that have 'Super' role, they might be able to delete/edit the data while the rest can only see it? 此外,为了在页面中启用某些链接/操作,例如对于具有“超级”角色的用户,他们可能能够删除/编辑数据,而其他人只能看到它?

For your information, I do not use the out of the box User management from the ASP.NET MVC (where the user is created in the .mdf database embedded to webapp), but I have developed my own user module (for authenticating, registering and deleting user). 为了您的信息,我不使用ASP.NET MVC中的开箱即用的用户管理(用户是在嵌入到webapp的.mdf数据库中创建的),但是我已经开发了自己的用户模块(用于身份验证,注册)并删除用户)。

So ..what is the best practice for this problem? 那么..这个问题的最佳做法是什么?

You would write a custom ValidationAttribute : http://msdn.microsoft.com/en-AU/library/system.componentmodel.dataannotations.validationattribute.aspx 您可以编写自定义ValidationAttributehttp//msdn.microsoft.com/en-AU/library/system.componentmodel.dataannotations.validationattribute.aspx

Basically, you inherit from ValidationAttribute , and override IsValid() : 基本上,您从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
    }
}

..then you apply it to controller actions: ..然后将其应用于控制器操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM