在注册时为用户分配角色

Assigning role to users upon Registration

我是 c# 的新手。我正在尝试创建一个 Web 应用程序,它将在使用身份 2.0 和 MVC5 注册后自动为用户分配 "User" 角色。

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                result = UserManager.AddToRole(user.Id, "User");

                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

当我运行上面的代码时,注册完成后出现以下错误

     Role User does not exist.

     Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

     Exception Details: System.InvalidOperationException: Role User does not exist.

      Source Error: 


      Line 156:                if (result.Succeeded)
      Line 157:                {
      Line 158:                    result = UserManager.AddToRole(user.Id, "User");
      Line 159:                   
      Line 160:                    await SignInManager.SignInAsync(user,                isPersistent:false, rememberBrowser:false);

如有任何建议,我们将不胜感激 谢谢

您需要先创建角色。将此添加到您的 Startup.Auth.cs 文件

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
roleManager.Create(new IdentityRole("User"));

如果您不使用 ApplicationDbContext 作为标识,请将您正在使用的上下文提供给 RoleStore 构造函数。