简体   繁体   中英

How to implement roles in ASP.NET MVC?

If I have a controller which has [authorize(role="admin")], how do I create the admin role and add a user to the role? Many people suggested I create a new class and many other changes but it's quite difficult to implement this and I'm wondering if there is a simpler way.

Here's what I have found.

Where should I put this?

        Roles.CreateRole("admin");

and where should i implement this

        Roles.AddUserToRole(User.Identity.Name,"admin");

You may use it in an ActionResult and it looks like this depending on implementation :

    public ActionResult Create(string RoleName)
    {
        Roles.CreateRole(RoleName);
        return RedirectToAction("Index");
    }

And again for adding role:

 public ActionResult AddToAdmin(User user)
    {           
        Roles.AddUserToRole(user.UserName, "admin");                    
        return RedirectToAction("Index");             
    }

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