在注册时为用户分配角色

时间:2015-07-18 12:29:08

标签: c# asp.net-mvc authentication authorization roles

我对c#很新。我正在尝试创建一个Web应用程序,它将为用户分配一个"用户"使用identity 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);

任何建议都将不胜感激 感谢

1 个答案:

答案 0 :(得分:1)

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

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

如果您没有使用ApplicationDbContext身份,请将您正在使用的上下文提供给RoleStore构造函数。

相关问题