Adding a role to an AspNetUserRoles table in ASP.NET Identity

I am using ASP.NET Identity 2.0 in my MVC application and I want to assign 2 default roles to the user who logs in for the first time by adding 2 entries to the AspNetUserRoles table UserId and RoleId . Is there a practical way to do this? Or I need to add these roles by default using DBContext and Entity Framework etc. (I am using EF Code First )? Any help would be greatly appreciated.

+5
source share
2 answers

After creating a custom post in the "Send Message" message

 var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); 

You can add roles

 await UserManager.AddToRoleAsync(user.Id, "role1"); await UserManager.AddToRoleAsync(user.Id, "role2"); 
+4
source

You can check in the AccountController method, Register (the one with HttpPost), something like: if (!MyDbContext.Users.Any()) {...}

And if there are no users, assign roles to the newly created user with: UserManager.AddToRoleAsync

+1
source

Source: https://habr.com/ru/post/1246451/


All Articles