InvalidOperationException:角色testRole不存在

问题描述 投票:0回答:1

我试图让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:Role TESTROLE不存在。

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

笔记:

  • 我在我的项目中使用PostgreSql,所以我用MSSQL创建了一个新项目并最终得到了同样的错误。
  • 我确保testRole在AspNetRoles表中。所以,这也没问题!
.net-core asp.net-core-mvc asp.net-identity
1个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.