【问题标题】:How to create roles in ASP.NET Core 2.2 and assign them to users如何在 ASP.NET Core 2.2 中创建角色并将其分配给用户
【发布时间】:2019-09-23 10:23:46
【问题描述】:

我正在使用 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();
                }
            }

        }

非常感谢为我的应用设置管理员的任何帮助。

【问题讨论】:

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


【解决方案1】:

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

public class ApplicationUser : IdentityUser
{

}

修改_LoginPartial.cshtml 以使用该类:

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

修改Data文件夹中的ApplicationDbContext.cs,分配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>();

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

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

【讨论】:

  • 它确实几乎完成了工作。它创建角色“管理员”并将其分配给我提供的用户,但是在按下导航栏中的登录按钮时收到错误消息。 InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'WebApplication1.Areas.Identity.Pages.Account.LoginModel'.
  • 您修改_LoginPartial.cshtml 以使用新的ApplicationUser 吗?
  • 搜索您的应用程序以找到任何 IdentityUser 存在?尝试用 ApplicationUser 替换
  • 看起来是这个问题,但是修改后,新角色并没有保存在数据库中。
  • 在 CreateUserRoles 中调试,一步一步确认问题出在哪里
猜你喜欢
  • 2017-07-17
  • 1970-01-01
  • 2019-12-18
  • 2015-08-01
  • 2013-01-02
  • 2021-05-01
  • 2014-03-11
  • 1970-01-01
  • 2017-08-30
相关资源
最近更新 更多