Korpin
Korpin

Reputation: 325

Create a new role with RoleManager

I created a context (with scaffolding) and also a user. I also set to play the db (and created a migration). This works perfectly! I would now just like to create a role and then assign it to a user.

For that, I modified my startup.cs file in order to proceed (I was not able to find a tutorial that shows how to create / assign a role with a different context than that of ApplicationDbContext).

I'm happy with the error in my code (at least I think), but I do not know how to handle it and what to replace the object.

So I created a CreateRoles method that receives a serviceProvider (of type IServiceProvider) and in this method I try to initialize the romes and then assign them to the different users of my db.

My concern is here (I think):

var RoleManager = serviceProvider.GetRequiredService > ();

Indeed, is I think used for the ApplicationDbContext except that I use jakformulaireContext.

My question is: what should I replace (if that's what I need to replace)?

Let me know if you need mode info or mode code!

Startup Class

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

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("[email protected]");

    if (user == null)
    {
        user = new jakformulaireUser()
        {
            UserName = "[email protected]",
            Email = "[email protected]",
            EmailConfirmed = true
        };
        await UserManager.CreateAsync(user, "Test123$");
    }
    await UserManager.AddToRoleAsync(user, "Member");


    jakformulaireUser user1 = await UserManager.FindByEmailAsync("[email protected]");

    if (user1 == null)
    {
        user1 = new jakformulaireUser()
        {
            UserName = "[email protected]",
            Email = "[email protected]",
            EmailConfirmed = true
        };
        await UserManager.CreateAsync(user1, "Test123$");
    }
    await UserManager.AddToRoleAsync(user1, "Admin");

}

}

Context

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

Upvotes: 2

Views: 4122

Answers (1)

itminus
itminus

Reputation: 25380

This error occurs typically when you create your own IdentityRole or when you forget to register the RoleManager.

  1. If you have customed the context by class jakformulaireContext : IdentityDbContext<YourAppUser, YourIdentityRole>, make sure anywhere you use the RoleManager<IdentityRole> service has be replaced with RoleManager< YourIdentityRole>

  2. Also, make sure the RoleManager<YourIdentityRole> has been registered . If you don't create your own version of IdentityRole, simply call .AddRoleManager<RoleManager<IdentityRole>>()

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

Upvotes: 2

Related Questions