如何在ASP.NET Core 2.2中创建角色并将其分配给用户

时间:2019-05-05 16:29:38

标签: c# asp.net asp.net-core asp.net-identity asp.net-core-2.2

我正在使用asp.net core 2.2默认网站模板和身份验证作为个人用户帐户。如何创建“管理员”角色并将其分配给用户,以便我可以在控制器中使用角色来过滤访问权限并让他们看到不同的页面。 这是我到目前为止在互联网上发现的内容,但由于它显示为ApplicationUser could not be found

,因此无法正常工作
private void CreateRoles(IServiceProvider serviceProvider)
        {

            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            Task<IdentityResult> roleResult;
            string email = "someone@somewhere.com";

            //Check that there is an Administrator role and create if not
            Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
            hasAdminRole.Wait();

            if (!hasAdminRole.Result)
            {
                roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
                roleResult.Wait();
            }

            //Check if the admin user exists and create it if not
            //Add to the Administrator role

            Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
            testUser.Wait();

            if (testUser.Result == null)
            {
                ApplicationUser administrator = new ApplicationUser();
                administrator.Email = email;
                administrator.UserName = email;

                Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!");
                newUser.Wait();

                if (newUser.Result.Succeeded)
                {
                    Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
                    newUserRole.Wait();
                }
            }

        }

在为我的应用程序提供管理员方面的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

第一步是创建ApplicationUser类,该类可用于扩展声明:

public class ApplicationUser : IdentityUser
{

}

修改_LoginPartial.cshtml以使用该类:

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

修改ApplicationDbContext.cs文件夹中的Data以分配ApplicationUserIdentityRole

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

修改Startup.cs以启用使用新的ApplicationUser和角色管理:

services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();

之后,您可以播种到板条箱角色并分配给用户,例如:

private async Task CreateUserRoles(IServiceProvider serviceProvider)
{
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

    IdentityResult roleResult;
    //Adding Admin Role
    var roleCheck = await RoleManager.RoleExistsAsync("Admin");
    if (!roleCheck)
    {
        //create the roles and seed them to the database
        roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
    }
    //Assign Admin role to the main User here we have given our newly registered 
    //login id for Admin management
    ApplicationUser user = await UserManager.FindByEmailAsync("v-nany@hotmail.com");
    await UserManager.AddToRoleAsync(user, "Admin");
}

要使用:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider serviceProvider)
{
    .......

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    CreateUserRoles(serviceProvider).Wait();
}

答案 1 :(得分:0)

您需要添加ApplicationUser类,该类也继承IdentityUser类。

 public class ApplicationUser : IdentityUser
    {
    }