Adding users to roles on registring failed ASP.NET

2019-06-11 08:22发布

问题:

I like to enable users to choose their role on register in asp.net mvc web application. I have previous add roles via asp.net addministration tool. Here is the code I am using in register methods

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


 [HttpPost]
    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);
    }

While in Register View I got this code

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

Roles are written in the database and users although. However UsersInRoles table is empty and I got this exception

System.Configuration.Provider.ProviderException: The role 'roleName' was not found.

Does anybody had the same problem?

回答1:

You should add roleName parameter to Register controller action for get selected by user roleName, or retrieve roleName from FormCollection, here is example Change your Register post action to:

        [HttpPost]
        public ActionResult Register(RegisterModel model, String roleName)
        {
            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);
        }