I'm trying to figure out how to enable and populate roles in my Razor Pages application.
By following various tutorials, ConfigureServices
in Startup.cs looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
// Set the default authentication policy to require users to be authenticated
services.AddControllers(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
But the call to AddDefaultIdentity
raises an exception.
System.InvalidOperationException: 'AddEntityFrameworkStores can only be called with a role that derives from IdentityRole.'
Can anyone see what I'm missing here? Also, I really want to know how to populate the roles.
Change your IdentityUser
to IdentityRole
like below:
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole>() //change this
.AddEntityFrameworkStores<ApplicationDbContext>();
Reference: