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

时间:2016-04-23 06:43:17

标签: asp.net-mvc asp.net-core asp.net-identity-3

我已经在Stackoverflow中查找了这个内容,到目前为止,似乎有很多关于在身份1中添加角色的问题& 2但在身份3中有所不同。

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

2 个答案:

答案 0 :(得分:7)

修改

<强>身份

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

修改

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

{{1}}

答案 1 :(得分:0)

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

在您的Startup.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();
  }

可能会对某人有所帮助:)