我找到了此答案,但它似乎不适合我的ASP Net Core项目。
I've found this answer but it doesn't seem to fit in my ASP Net Core project.
我想了解的事情:
- 如何添加自定义角色。我什至直接查看了我的MySQL数据库(表 aspnetroles ),但是我不知道用什么作为 Id 和 ConcurrencyStamp 。
- 我在哪里将代码植入这些具有以下新角色的数据库中:启动?在 AccountController 下的 Register 中?
- 如何将此新角色与用户?我什至浏览了表格,不知道如何分配数据(没有 user2role 或 aspnetusers.role_id )。
- How can I add a custom role. I've even looked directly in my MySQL database (table aspnetroles), but I don't know what to use as Id and ConcurrencyStamp.
- Where do I put the code to seed the database with these new roles: in Startup? in Register under AccountController?
- How do I tie this new role to a user? I've even looked through the tables and I don't know how to assign the data (there is no user2role or aspnetusers.role_id).
您可以通过创建 CreateRoles 方法。这有助于检查是否创建了角色,如果没有创建角色,则可以创建角色;在应用程序启动时。
You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider) { //adding customs roles : Question 1 var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); string[] roleNames = { "Admin", "Manager", "Member" }; IdentityResult roleResult; foreach (var roleName in roleNames) { var roleExist = await RoleManager.RoleExistsAsync(roleName); if (!roleExist) { //create the roles and seed them to the database: Question 2 roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName)); } } //Here you could create a super user who will maintain the web app var poweruser = new ApplicationUser { UserName = Configuration["AppSettings:UserName"], Email = Configuration["AppSettings:UserEmail"], }; string userPWD = Configuration["AppSettings:UserPassword"]; var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]); if(_user == null) { var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD); if (createPowerUser.Succeeded) { //here we tie the new user to the role : Question 3 await UserManager.AddToRoleAsync(poweruser, "Admin"); } } }您可以从Startup类的 Configure 方法中调用 await CreateRoles(serviceProvider); 方法。 确保在 Configure 类中将 IServiceProvider 作为参数。
and then you could call the await CreateRoles(serviceProvider); method from the Configure method in the Startup class. ensure you have IServiceProvider as a parameter in the Configure class.
编辑:如果您使用的是ASP.NET core 2.x,我在这里的文章将提供非常详细的体验。 这里
更多推荐
如何将自定义角色添加到ASP.NET Core
发布评论