且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将自定义角色添加到ASP.NET Core

更新时间:2022-11-18 15:37:31

您可以通过创建 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,我在这里的文章将提供非常详细的体验。
这里