使用RoleManager创建新角色

时间:2018-12-14 15:20:59

标签: c# asp.net asp.net-mvc model-view-controller asp.net-core

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

为此,我修改了startup.cs文件以继续进行操作(我找不到一个教程,该教程显示了如何使用与ApplicationDbContext不同的上下文来创建/分配角色)。

我对代码中的错误感到满意(至少在我看来),但我不知道如何处理该错误以及如何替换该对象。

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

我的关注在这里(我认为):

  

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

1 个答案:

答案 0 :(得分:2)

通常在您创建自己的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>()