2 回答
TA贡献1871条经验 获得超8个赞
当您调用时,await userManager.UpdateAsync(user);
您正在更新用户模型及其所有相关数据。您需要将新角色添加到现有角色列表中,而不是创建新的空列表并添加新记录。
TA贡献1831条经验 获得超10个赞
尝试下面的代码来添加新角色
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public HomeController(ApplicationDbContext context
, UserManager<ApplicationUser> userManager
, RoleManager<IdentityRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<IActionResult> CreateUserAndRole()
{
await _userManager.CreateAsync(new ApplicationUser { UserName = "test@outlook.com", Email = "test@outlook.com" });
await _roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
await _roleManager.CreateAsync(new IdentityRole { Name = "Administrator" });
return Ok();
}
public async Task<IActionResult> AddAdminRoleToUser()
{
ApplicationUser user = _context.Users.FirstOrDefault(u => u.UserName == "test@outlook.com");
var role = await _roleManager.FindByNameAsync("Admin");
user.Roles.Add(new IdentityUserRole<string> { RoleId = role.Id, UserId = user.Id });
await _userManager.UpdateAsync(user);
return Ok();
}
public async Task<IActionResult> AddAdministratorRoleToUser()
{
ApplicationUser user = _context.Users.FirstOrDefault(u => u.UserName == "test@outlook.com");
var role = await _roleManager.FindByNameAsync("Administrator");
user.Roles.Add(new IdentityUserRole<string> { RoleId = role.Id, UserId = user.Id });
await _userManager.UpdateAsync(user);
return Ok();
}
- 2 回答
- 0 关注
- 248 浏览
添加回答
举报