【发布时间】: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