简体   繁体   中英

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).

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

Basically, you inherit from ValidationAttribute , and override 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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