简体   繁体   中英

ASP .net create Role problem with RoleManager

I'm writing ASP.Net app using Jetbrains Rider. I'm using Identity. Mine ApplicationDbContext looks like that:

public class BoardGameNETProjectContext : IdentityDbContext<IdentityUser>

{

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

}

And in Program.cs i have this line:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new BoardGameNETProjectContext()));

When I'm building I've got error message that parameter "options" is missing. I don't know how to fix that, I just wanted to add "Admin" role just like in this tutorial: link

I assume that you are using asp.net 6 project - if so you can simply replace

var roleManager = new RoleManager<IdentityRole>(
    new RoleStore<IdentityRole>(
        new BoardGameNETProjectContext()));

with

// where you have this line
var app = builder.Build();

var scope = app.Services
    .GetService<IServiceScopeFactory>()
    ?.CreateScope();

if (scope is not null)
{ 
    using (scope)
    {
        var roleManager = scope
            .ServiceProvider
            .GetService<RoleManager<IdentityRole>>();

        // .. then use the RoleManager
    }
}

but you should ensure that you are adding the right identity:

services.AddIdentity<IdentityUser, IdentityRole>()

... instead of the Default Identity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM