【问题标题】:Identity usermanager cannot find the Role身份用户管理器找不到角色
【发布时间】:2016-12-14 11:09:24
【问题描述】:

我在成功创建用户后尝试将用户添加到角色。

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
  • 当然,角色是在种子方法中创建的,我验证它存在于数据库中

标签: c# asp.net-core


【解决方案1】:

我在种子方法中发现了问题。但是我不明白。

在种子方法中,我使用 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 中成功创建的角色。

但是当采取行动时,从未找到角色。

我用 RoleManager 替换了 RoleStore

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

就像魔术一样,一切都解决了。我将进一步研究差异和原因以进一步了解它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2021-11-18
    • 2015-09-16
    • 2020-01-24
    • 1970-01-01
    相关资源
    最近更新 更多