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

5 c# asp.net asp.net-identity asp.net-core 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();
                }
            }

        }
Run Code Online (Sandbox Code Playgroud)

为我的应用程序设置管理员的任何帮助将不胜感激。

Nan*_* Yu 7

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

public class ApplicationUser : IdentityUser
{

}
Run Code Online (Sandbox Code Playgroud)

修改_LoginPartial.cshtml以使用该类:

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
Run Code Online (Sandbox Code Playgroud)

修改ApplicationDbContext.csinData文件夹以分配ApplicationUserIdentityRole

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

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

services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

之后,您可以播种以创建角色并分配给用户,例如:

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");
}
Run Code Online (Sandbox Code Playgroud)

使用:

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();
}
Run Code Online (Sandbox Code Playgroud)