asp Identity 2.0 adding new roles and adding user to roles

微笑、不失礼 提交于 2019-12-04 18:25:04

问题


I'm having trouble understanding the new Identity stuff. I'm trying to figure out how to add new roles and add user's to those roles. I'm trying to create a role management page and a user management page for my application and need to be able to do those two things. Everytime i try to add a role to a user like this: System.Web.Security.Roles.AddUserToRole("Andy", "admin"); I get "The Role Manager feature has not been enabled." I don't have a custom role provider and i tried turning role manager to enabled but just got an error about not having a role provider. I figured Identity had all this built in already? Can somebody help me through this?


回答1:


System.Web.Security is the old ASP.NET Membership framework. ASP.NET Identity is in the namespace Microsoft.AspNet.Identity. Use a RoleManager to create roles, and a UserManager to add users to roles.

using (var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)) 
{
    roleManager.Create(new IdentityRole("Administrator"));
}

using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)))
{
    var user = new ApplicationUser { UserName = "admin" };
    userManager.Create(user, "admin321");
    userManager.AddToRole(user.Id, "Administrator");
}


来源:https://stackoverflow.com/questions/23187028/asp-identity-2-0-adding-new-roles-and-adding-user-to-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!