Asp.Net core MVC6 如何在 Identity 3 中初始添加角色

Asp.Net core MVC6 How to initially add roles in Identity 3

我在 Whosebug 中查找过这个,到目前为止似乎有很多关于在 Identity 中添加角色的问题 1 & 2 但在 Identity 3 中却有所不同。

我想在数据库中播种角色。我只有两个。我打算使用已注入 class 的 _roleManager。没关系。我的问题是..似乎没有任何方法可以实际添加角色..使用 CreateAsync 是为了将用户添加到角色..你如何编码使用“_userManager”添加角色或者你必须这样做另一种方式?

编辑

身份

IdentityRoleManager用于创建角色,UserManager用于将用户添加到角色。 这是一个为您指明正确方向的示例。下面的代码用于创建一个新角色 Administrator

if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "Administrators can do something with data");
                roleManager.Create(newRole);
            }  

编辑

此外,这是将用户添加到角色,这也是一个示例:

 \assuming you test if the user has been assigned to the role "Administrator" before adding them to that role

 if(RoleAdministrator == true){
           userManager.AddToRole(User.Id, "Administrator");
       }
public class SeedData
{
    private const string _adminRoleName = "admin";
    private string _adminEmail = "admin@demo.com";
    private string _adminPassword = "P@ssw0rd!PK";

    private string[] _roles = new string[] { _adminRoleName, "supervisor" };

    private readonly RoleManager<IdentityRole<Guid>> _roleManager;
    private readonly UserManager<ApplicationUser> _userManager;

    public  static async Task Run(IServiceProvider serviceProvider)
    {
        using (var serviceScope =serviceProvider
                                 .GetRequiredService<IServiceScopeFactory>()
                                 .CreateScope())
        {
            var instance = serviceScope.ServiceProvider.GetService<SeedData>();
            await instance.Initialize();

            var context = serviceScope.ServiceProvider.GetService<AppDbContext>();
            if (!context.Products.Any())
            {
               // Seed Other entities Here
            }

            await context.SaveChangesAsync();
        }
    }

    public SeedData(UserManager<ApplicationUser> userManager, 
                                  RoleManager<IdentityRole<Guid>> roleManager)
    {
        _roleManager = roleManager;
        _userManager = userManager;
    }

    public async Task Initialize()
    {
        foreach (var role in _roles)
        {
            if (!await _roleManager.RoleExistsAsync(role))
            {
                await _roleManager.CreateAsync(new IdentityRole<Guid>(role));
            }
        }

        var adminUsers = await _userManager.GetUsersInRoleAsync(_adminRoleName);
        if (!adminUsers.Any())
        {
            var adminUser = new ApplicationUser()
            {
                Id = Guid.NewGuid(),
                Email = _adminEmail,
                UserName = _adminEmail
            };

            var result = await _userManager.CreateAsync(adminUser, _adminPassword);
            if(result.Success)
            {
               await _userManager.AddToRoleAsync(adminUser, _adminRoleName);
            }
       }         
   }
}

在你的Program.cs

public static void Main(string[] args)
{
     var host = BuildWebHost(args);

     using (var scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         try
         {
              SeedData.Run(services).Wait();
         }
         catch (Exception ex)
         {
             var logger = services.GetRequiredService<ILogger<Program>>();
             logger.LogError(ex, "Error while seeding database.");
         }
     }

      host.Run();
  }

可能对某人有帮助:)