首页 > 解决方案 > 使用 RoleManager 创建新角色

问题描述

我创建了一个上下文(带脚手架)和一个用户。我还设置播放数据库(并创建了迁移)。这完美!我现在只想创建一个角色,然后将其分配给用户。

为此,我修改了我的 startup.cs 文件以继续(我无法找到说明如何创建/分配具有与 ApplicationDbContext 不同上下文的角色的教程)。

我对代码中的错误感到满意(至少我认为),但我不知道如何处理它以及替换对象的内容。

因此,我创建了一个接收 serviceProvider(类型为 IServiceProvider)的 CreateRoles 方法,并在此方法中尝试初始化 romes,然后将它们分配给我的数据库的不同用户。

我关心的是这里(我认为):

var RoleManager = serviceProvider.GetRequiredService > ();

事实上,我认为除了我使用 jakformulaireContext 之外,它是否用于 ApplicationDbContext。

我的问题是:我应该更换什么(如果那是我需要更换的)?

如果您需要模式信息或模式代码,请告诉我!

创业班

公共类启动{公共启动(IConfiguration配置){配置=配置;}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<jakformulaireContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("jakformulaireContextConnection")));
    services.AddDefaultIdentity<jakformulaireUser>(configg =>
    {
        configg.SignIn.RequireConfirmedEmail = true;
    }).AddEntityFrameworkStores<jakformulaireContext>(); ;


    var config = new AutoMapper.MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new MappingProfile());
    });
    var mapper = config.CreateMapper();
    services.AddSingleton(mapper);

    //services.AddAutoMapper();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddDistributedMemoryCache();

    services.AddSession();

    // requires
    // using Microsoft.AspNetCore.Identity.UI.Services;
    // using WebPWrecover.Services;
    services.AddSingleton<IEmailSender, EmailSender>();
    services.Configure<AuthMessageSenderOptions>(Configuration);

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

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

    app.UseAuthentication();

    app.UseCors("CorsPolicy");

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

    //CreateRoles(serviceProvider).Wait();
}

private async Task CreateRoles(IServiceProvider serviceProvider)
{
    //initializing custom roles   
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<jakformulaireUser>>();
    string[] roleNames = { "Guest", "Member", "Admin" };
    IdentityResult roleResult;

    foreach (var roleName in roleNames)
    {
        var roleExist = await RoleManager.RoleExistsAsync(roleName);
        if (!roleExist)
        {
            //create the roles and seed them to the database: Question 1  
            roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
        }
    }

    jakformulaireUser user = await UserManager.FindByEmailAsync("test@test.com");

    if (user == null)
    {
        user = new jakformulaireUser()
        {
            UserName = "test@test.com",
            Email = "test@test.com",
            EmailConfirmed = true
        };
        await UserManager.CreateAsync(user, "Test123$");
    }
    await UserManager.AddToRoleAsync(user, "Member");


    jakformulaireUser user1 = await UserManager.FindByEmailAsync("test@live.be");

    if (user1 == null)
    {
        user1 = new jakformulaireUser()
        {
            UserName = "test@live.be",
            Email = "test@live.be",
            EmailConfirmed = true
        };
        await UserManager.CreateAsync(user1, "Test123$");
    }
    await UserManager.AddToRoleAsync(user1, "Admin");

}

}

语境

public class jakformulaireContext : IdentityDbContext<jakformulaireUser>
{
    public jakformulaireContext(DbContextOptions<jakformulaireContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

标签: c#asp.netasp.net-mvcmodel-view-controllerasp.net-core

解决方案


此错误通常发生在您创建自己的IdentityRole或忘记注册RoleManager.

  1. 如果您已通过 自定义上下文class jakformulaireContext : IdentityDbContext<YourAppUser, YourIdentityRole>请确保您使用该RoleManager<IdentityRole>服务的任何地方都已替换为RoleManager< YourIdentityRole>

  2. 另外,请确保RoleManager<YourIdentityRole>已注册. 如果您不创建自己的版本IdentityRole,只需调用.AddRoleManager<RoleManager<IdentityRole>>()

     services.AddIdentity<jakformulaireUser, IdentityRole>() 
        .AddRoleManager<RoleManager<IdentityRole>>()  // make sure the roleManager has been registered .
        .AddDefaultUI() 
        // other features ....
        .AddEntityFrameworkStores<jakformulaireContext>()
    

推荐阅读