0
我想在成功創建用戶後將用戶添加到角色。身份用戶管理員找不到角色
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (!ModelState.IsValid) return View(model);
var user = new ApplicationUser
{
UserName = model.PhoneNumber,
PhoneNumber = model.PhoneNumber,
NationalId = model.NationalId,
FullName = model.FullName
};
var result = await _userManager.CreateAsync(user, model.NationalId);
if (result.Succeeded)
{
var res = await _userManager.AddToRoleAsync(user, "Admin");
await _signInManager.SignInAsync(user, false);
_logger.LogInformation(3, "Applicant created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
// If we got this far, something failed, redisplay form
return View(model);
}
但是,我得到這個錯誤。
處理請求時發生未處理的異常。
InvalidOperationException:角色ADMIN不存在。
更新: 我叫
var myrole = await _roleManager.FindByNameAsync("Admin");
,並返回null。但是當我檢查
var roles = _roleManager.Roles
我得到的所有角色,包括「管理」
您是否在添加用戶之前「創建」IdentityRole? – tmg
當然,角色是在種子方法中創建的,並且我證實它存在於數據庫中 – Osama