如何向 ASP.NET Core 添加自定义角色 [英] How to add custom roles to ASP.NET Core

查看:26
本文介绍了如何向 ASP.NET Core 添加自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个答案,但它似乎不适合我的 ASP Net Core 项目.>

我想了解的事情:

  • 如何添加自定义角色.我什至直接查看了我的 MySQL 数据库(表 aspnetroles),但我不知道将什么用作 IdConcurrencyStamp.
  • 在哪里放置代码以使用这些新角色为数据库做种:在Startup 中?在 RegisterAccountController?
  • 如何将这个新角色与用户绑定?我什至查看了表格,但我不知道如何分配数据(没有 user2roleaspnetusers.role_id).

解决方案

您可以通过在启动类中创建一个 CreateRoles 方法来轻松完成此操作.这有助于检查角色是否已创建,如果没有,则创建角色;在应用程序启动时.像这样.

私有异步任务 CreateRoles(IServiceProvider serviceProvider){//添加海关角色:问题1var RoleManager = serviceProvider.GetRequiredService>();var UserManager = serviceProvider.GetRequiredService>();string[] roleNames = { "Admin", "Manager", "Member" };IdentityResult 角色结果;foreach (var roleName in roleNames){var roleExist = await RoleManager.RoleExistsAsync(roleName);如果 (!roleExist){//创建角色并将它们播种到数据库中:问题2roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));}}//在这里你可以创建一个超级用户来维护网络应用程序var poweruser = 新应用程序用户{UserName = Configuration["AppSettings:UserName"],电子邮件 = 配置["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);如果(createPowerUser.Succeeded){//在这里我们将新用户绑定到角色:问题 3等待 UserManager.AddToRoleAsync(poweruser, "Admin");}}}

然后您可以从 Startup 类中的 Configure 方法调用 await CreateRoles(serviceProvider); 方法.确保您将 IServiceProvider 作为 Configure 类中的参数.

如果您使用的是 ASP.NET core 2.x,我的这篇文章提供了非常详细的体验.这里

I've found this answer but it doesn't seem to fit in my ASP Net Core project.

Things I am trying to understand:

  • 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).

解决方案

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");

            }
       }
    }

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.

Edit: If you're using ASP.NET core 2.x, my article here provides a much detailed experience. here

这篇关于如何向 ASP.NET Core 添加自定义角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆