我正在使用 Asp.net核心 Application.I想在我的应用程序中使用基于角色的声明,我尝试过以下代码,但它不起作用。它不在db中创建aspnetrolesclaim表。我做错了吗?
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
CreateRolesAndAdminUser(app);
}
private async Task CreateRolesAndAdminUser(IApplicationBuilder app)
{
var _roleManager = app.ApplicationServices.GetRequiredService<RoleManager<ApplicationRole>>();
var roleExists = await _roleManager.RoleExistsAsync("Admin");
if (!roleExists)
{
var role = new ApplicationRole()
{
Name = RoleName.SuperUser,
NormalizedName = RoleName.SuperUser.ToUpper(),
};
await _roleManager.CreateAsync(role);
await _roleManager.AddClaimAsync(role, new Claim("User","Create"));
await _roleManager.AddClaimAsync(role, new Claim("User","Edit"));
await _roleManager.AddClaimAsync(role, new Claim("User", "Delete"));
}
string adminUserEmail = "admin@adminstore.com";
string adminPwd = "admin@123";
var _userManager = app.ApplicationServices.GetRequiredService<UserManager<ApplicationUser>>();
var checkAppUser = await _userManager.FindByEmailAsync(adminUserEmail);
if (checkAppUser == null)
{
ApplicationUser newAppUser = new ApplicationUser
{
Email = adminUserEmail,
UserName = adminUserEmail,
NormalizedEmail = adminUserEmail.ToUpper(),
NormalizedUserName = adminUserEmail.ToUpper(),
};
await _userManager.CreateAsync(newAppUser, adminPwd);
await _userManager.AddToRoleAsync(newAppUser,"Admin");
}
}