在注册时为用户分配角色

本文关键字:分配 角色 用户 注册 | 更新日期: 2023-09-27 18:03:17

我是c#新手。我试图创建一个web应用程序,将在使用身份2.0和MVC5注册时自动分配用户"用户"角色。

    // 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构造器。