2016-12-14 60 views
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 

我得到的所有角色,包括「管理」

+0

您是否在添加用戶之前「創建」IdentityRole? – tmg

+0

當然,角色是在種子方法中創建的,並且我證實它存在於數據庫中 – Osama

回答

0

我發現在種子法的問題。但我不明白。

在種子法中,我使用了RoleStore來添加角色。

var roles = new[] {"Admin", "Applicant", "Student", "Role1", "Role2", "Role3", "Role4"}; 
     foreach (var role in roles) 
     { 
      var roleStore = new RoleStore<IdentityRole>(context); 

      if (!context.Roles.Any(r => r.Name == role)) 
       await roleStore.CreateAsync(new IdentityRole(role)); 
     } 

在數據庫表AspNetRoles中成功創建的角色。

但是當起作用時,角色從未找到。

我取代Rolestore的與RoleManager

await _roleManager.CreateAsync(new IdentityRole(role)); 

和像變魔術一樣,它都解決了。我會進一步研究差異和原因,以便更多地理解它。

相關問題