如何在ASP.Net Core中创建“ RoleManager <identityrole>”?

时间:2018-12-30 20:32:27

标签: c# asp.net-mvc

我无法在我的应用程序中使用RoleManager。我正在尝试将Admin用户播种到.NET Core Web应用程序中,并且我希望该用户具有一个名为“ canEdit”的角色。我目前所拥有的会产生此错误:

System.InvalidOperationException:'没有注册类型为'Microsoft.AspNetCore.Identity.RoleManager`1 [Microsoft.AspNetCore.Identity.IdentityRole]'的服务。'

我尝试了多种方法来做到这一点。我尝试使用服务提供者来执行此操作,进行依赖项注入等,但是它们都给出相同的错误。

Startup.cs的Configure方法中的ServiceProvider:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
DbInitializer dbi = new DbInitializer(roleManager);
dbi.Initialize(context, userManager);

DBInitializer类:

构造函数:

private readonly RoleManager<IdentityRole> rm;

    public DbInitializer(RoleManager<IdentityRole> rm)
    {
        this.rm = rm;
    }

CreateAdmin方法:

private async Task CreateAdmin(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
    {
        IdentityResult ir;
        ir = await rm.CreateAsync(new IdentityRole("canEdit"));
        IdentityRole canEdit = new IdentityRole("canEdit");
        ApplicationUser admin = new ApplicationUser
        {
            UserName = "Member1@email.com"
        };
        if (context.Users.Where(u => u.UserName == admin.UserName).Count() == 0)
        {
            userManager.CreateAsync(admin, "Password123!").Wait();
            userManager.AddToRoleAsync(admin, "canEdit").Wait();
        }
    }

CreateUsers方法:

private void CreateUsers(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
    {

        CreateAdmin(userManager, context).Wait();

        ApplicationUser customer1 = new ApplicationUser
        {
            UserName = "Customer1@email.com"
        };
        if (context.Users.Where(u => u.UserName == customer1.UserName).Count() > 0)
        {
            userManager.CreateAsync(customer1, "Password123!").Wait();
        }

对于customer2、3、4、5重复一遍。我可以通过取消创建我可能不需要的对象(在存在电子邮件的情况下)的需要来优化此方法,但是我试图取消这种方法和CreateAdmin方法,然后再进行优化。不幸的是,然后我遇到了无法修复的错误。

最终目标是让DbInitializer类为5个常规用户和1个具有额外权限/声明的管理员用户播种。

1 个答案:

答案 0 :(得分:0)

您是否已注册身份服务? 另外,当我使用.Wait()而不是等待时,我也遇到了问题。

  services.AddIdentity<ApplicationUser,IdentityRole>(options=>
        {
            options.User.RequireUniqueEmail = true;               
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;      

        })
            .AddDefaultTokenProviders()
            .AddDefaultUI()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddAuthorization();
        services.AddAuthentication();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 

如果这有帮助,这就是我播种Db的方式。

  public SeedDataBase(IServiceProvider _serviceProvider, ApplicationDbContext _context)
    {
        serviceProvider = _serviceProvider;
        context = _context;

    }
    private IServiceProvider serviceProvider;
    private ApplicationDbContext context;
    private ApplicationUser superUser;

    public async Task Seed()
    {

        await CreateSuperUser();
        await SeedDb();
    }
    private async Task CreateSuperUser()
    {
        var _userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        var userExists = await _userManager.GetUsersInRoleAsync("FULLADMIN");

        if (userExists.Count() < 1)
        {
            var _roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var _signinManger = serviceProvider.GetRequiredService<SignInManager<ApplicationUser>>();

            superUser = new ApplicationUser()
            {
                UserName = "superuser@superuser.com",
                Email = "superuser@superuser.com",
                FirstName = "Super",
                LastName = "User",
                AccountCreationDate = DateTime.Now.ToShortDateString(),
                Access = ApplicationUser.Permissions.FullAdmin
            };
            var permissions = Enum.GetNames(typeof(ApplicationUser.Permissions));

            foreach (var s in permissions)
            {
                await _roleManager.CreateAsync(new IdentityRole(s));
            }
            await _userManager.CreateAsync(superUser, "SecureP@ssword1234");
            await _userManager.AddToRoleAsync(superUser, Enum.GetName(typeof(ApplicationUser.Permissions), superUser.Access));
        }
    }