【问题标题】:InvalidOperationException: Role testRole does not existInvalidOperationException:角色 testRole 不存在
【发布时间】:2017-12-23 22:21:44
【问题描述】:

我试图让 accountController 自动为每个新注册的用户分配角色,所以我最终做了这样的事情:

public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);
                //there is where the error is being raised.
                await _userManager.AddToRoleAsync(user, "testRole");

                if (result.Succeeded)
                {
                 //here goes some code
                 //have also adding this line of code inside this if stmt
                //await _userManager.AddToRoleAsync(user, "testRole");
                }
                AddErrors(result);
            }
            return View(model);
        }

我做了 StackOverFlow 上其他帖子推荐的操作,但是我一直遇到这个错误: InvalidOperationException:角色 TESTROLE 不存在。

Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore+d__34.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) Microsoft.AspNetCore.Identity.UserManager+d__104.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.GetResult() WebApplication2.Controllers.AccountController+d__17.MoveNext() 在 AccountController.cs 中

注意事项:

  • 我在我的项目中使用 PostgreSql,所以我创建了一个新项目 使用 MSSQL 并以同样的错误告终。
  • 我已确保 testRole 位于 AspNetRoles 表中。所以,这也没有问题!

【问题讨论】:

  • TestRole 是否存在于 AspNetRoles 表中?
  • 如果你决定回到 PostgreSQL,它也可以在那里工作
  • 非常感谢它确实对我的项目有效。我没有注意到标准化的是那里的交易破坏者!我再次感谢你!
  • 这是一个错误的假设,因为 MS 假设有人不会填写,但他们会在查询期间检查它

标签: .net-core asp.net-core-mvc asp.net-identity


【解决方案1】:

所以 testRole 是确切的名称,然后会被标准化为 TESTROLE TestRole 是如何创建的?我这样说是因为 Identity 寻找标准化版本。异常很明显,在这种情况下它不存在。基本上,如果您没有使用 RoleManager,那么您创建角色的方式就有问题

创建角色的另一种方法是使用您的数据库上下文并以这种方式添加新角色,但如果您没有为 NormalizedName 字段条目使用大写字母,那么您将收到此错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2015-01-23
    • 1970-01-01
    • 2015-03-28
    • 2017-01-23
    • 2019-06-08
    • 1970-01-01
    相关资源
    最近更新 更多