如何在ASP.NET Core 2.2中创建角色并将其分配给用户 [英] How to create roles in ASP.NET Core 2.2 and assign them to users

查看:108
本文介绍了如何在ASP.NET Core 2.2中创建角色并将其分配给用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using asp.net core 2.2 default web site template and authentication selected as individual user account. How can i create an "Admin" role and assign it to a user so that i can use role in controller to filter the access and let them see different pages. Here is what i found on the internet until now, but it doesn't work, because it says : 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();
                }
            }

        }

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

Any help in having an Admin for my app will be greatly appreciated.

推荐答案

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

The first step is to create the ApplicationUser class which could be used to extend claims :

public class ApplicationUser : IdentityUser
{

}

修改_LoginPartial.cshtml以使用该类:

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

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

Modify the ApplicationDbContext.cs in Data folder to assign ApplicationUser and IdentityRole :

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

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

Modify the Startup.cs to enable using the new ApplicationUser and role management :

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

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

After that , you could seed to crate role and assign to user like :

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

这篇关于如何在ASP.NET Core 2.2中创建角色并将其分配给用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆