Chriz L

Chriz L

  • NA
  • 220
  • 49k

Web forms - Manage users and roles (Identity 2.2.1 )

Oct 31 2016 5:22 AM
Hello,
 
I want to build an admin panel where the admin can create roles,users, assign users to roles and reset passwords. I'm using Identity 2.2.1 with web forms
 
I would appreciate any kind of help. Thank you in advance.
 
I' m having problem with the following two.  
 
Resetting the password
I tried using the default ResetPassword.aspx in Account folder but I get the following error "An error has occurred" .
 
Create role and assign role at the same time:
 I'm using the following code:
  1. protected void btnAssignRole_Click1(object sender, EventArgs e)  
  2.        {  
  3.            RoleActions role = new RoleActions();  
  4.   
  5.            role.AddUserAndRole(roleTxt.Text, userTxt.Text, emailTxt.Text, passTxt.Text);  
  6.        }  
 
but I get the following error "An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code. Additional information: UserId not found." in RoleActions.cs
 
  1. internal void AddUserAndRole(String role, String user, String email, String pass)  
  2.        {  
  3.            Models.ApplicationDbContext context = new ApplicationDbContext();  
  4.            IdentityResult IdRoleResult;  
  5.            IdentityResult IdUserResult;  
  6.   
  7.            var roleStore = new RoleStore<IdentityRole>(context);  
  8.  
  9.            var roleMgr = new RoleManager<IdentityRole>(roleStore);  
  10.   
  11.            if (!roleMgr.RoleExists(role))  
  12.            {  
  13.                IdRoleResult = roleMgr.Create(new IdentityRole { Name = role });  
  14.            }  
  15.   
  16.            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));  
  17.            var appUser = new ApplicationUser  
  18.            {  
  19.                UserName = user,  
  20.                Email = email  
  21.            };  
  22.            IdUserResult = userMgr.Create(appUser, pass);  
  23.   
  24.                if (!userMgr.IsInRole(user, role))  
  25.                {  
  26.                IdUserResult = userMgr.AddToRole(user, role);  
  27.            }  
  28.        }                 

Answers (4)