How to use Roles in ASP.NET Core 2.1?

asked7 years ago
last updated7 years ago
viewed19.8k times
Up Vote18Down Vote

I've created a test project using:

dotnet new razor --auth Individual --output Test

This creates a Startup.cs that contains:

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<ApplicationDbContext>(options =>
        options.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

I want to seed some users and roles. Both users and roles will use the same store (SQLite). I'm using a static class for seeding which it's called from Program.

I can seed users, but not roles, since the above does not seem to inject a RoleManager.

In ASP.NET Core 2.0 the following is used:

services.AddIdentity<IdentityUser, IdentityRole>()

I'm guessing AddDefaultIdentity is new in 2.1 but the problem is that it does not inject a RoleMnager, so what should I do?