无法自动添加角色

时间:2012-04-15 01:01:44

标签: c# asp.net asp.net-mvc-3 forms-authentication

我的帐户控制器出现以下错误:

The role 'roleName' was not found.

但我有两个角色管理员和游戏玩家

我的注册表视图中的下拉列表将其选中:

   <label for="roleName">Select Role:</label>
    @Html.DropDownList("roleName")
    @Html.ValidationMessage("roleName")

在我的帐户控制器中,我有以下内容:

  //
        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            ViewData["roleName"] = new SelectList(Roles.GetAllRoles(), "roleName");
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(model.UserName, "roleName");
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }

                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

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

        }

我不知道为什么会这样?

1 个答案:

答案 0 :(得分:1)

看起来问题就在这里:

Roles.AddUserToRole(model.UserName, "roleName");

我猜你并不是故意把“roleName”写成文字。可能 model.RoleName 或“User”,或者您的角色提供程序中存在的角色?