SKale
SKale

Reputation: 571

Adding a role for user after registration in MVC 5

I want to add newly registered user to a generic "User" role in my application. I am using ASP.NET Identity. My code below returns a cryptic error - Exception Details: System.Configuration.Provider.ProviderException: The role '' was not found.

Do I need to instantiate something in my account controller (role manager etc)? Here my code in the AccountController Register POST action.

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            var person = new Person() { 
                UserName = user.UserName, 
                UserId = user.Id, 
                LastName = model.LastName, 
                FirstName = model.FirstName, 
                Email = model.Email, 
                PhoneCell = model.PhoneCell };
                Roles.AddUserToRole(model.UserName, "User");
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                db.People.Add(person);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

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

Upvotes: 25

Views: 41261

Answers (2)

ASPCoder1450
ASPCoder1450

Reputation: 1651

If you're using the built in authentication manager and Account Controller then this will do it:

UserManager.AddToRole(user.Id, "<Role>");

Upvotes: 21

Lin
Lin

Reputation: 15188

You need to use UserManager to add role to the user. See below:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        using (var context = new ApplicationDbContext())
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);

                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);
                userManager.AddToRole(user.Id, "User");

                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);                
        }
    }

Upvotes: 52

Related Questions