Search code examples
asp.netasp.net-mvcasp.net-mvc-5asp.net-identityasp.net-roles

Roles Create New DataBase When I Add a user to a role in MVC 5


i create my own database and add user identity table to this by change the connection string. now my connection string is this:

when i create a new user it worked well. but when i change the Register(RegisterViewModel model) in RegisterControler to add a user to a role like this code: public async Task Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //add user to member role******************
                if (!Roles.RoleExists("Member"))
                    Roles.CreateRole("Member");
                Roles.AddUserToRole(model.Email, "Member");
                //*******************************************

                await SignInAsync(user, isPersistent: false);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

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

user registerd but dont add to member Role! and it seem there is another connection string for Roles! beacause whene run this code ASPNETDB.MDF created in App_Data!

Please help me to solve this problem


Solution

  • In order to create roles in asp.net identity, you need to use AspNetRoleManager same as you are currently using AspNetUserManager.

    The AspNetUserManager may looks like below.

    public class AspNetRoleManager : RoleManager<IdentityRole, string>
        {
            public AspNetRoleManager(IRoleStore<IdentityRole, string> roleStore)
                : base(roleStore)
            {
            }
    
            public static AspNetRoleManager Create(IdentityFactoryOptions<AspNetRoleManager> options, IOwinContext context)
            {
                return new AspNetRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<YourDataContext>()));
            }
        }
    

    Then you need to register AspNetRoleManager in the owin startup. Same like the AspNetUserManager.

    app.CreatePerOwinContext<AspNetRoleManager>(AspNetRoleManager.Create);
    

    After that you can use it inside the controller to create roles.

    var roleManager = HttpContext.GetOwinContext().Get();

    // Check for existing roles

    var roleManager = HttpContext.GetOwinContext().Get<AspNetRoleManager>();
    var roleExists = await roleManager.RoleExistsAsync("Member");
    
    if (!roleExists)
    {
         var role = new IdentityRole();
         role.Name = "Member";
         var result = roleManager.CreateAsync(role);
    }
    

    Then add new role to the user.

    var user = await UserManager.FindByEmailAsync(model.Email);
    var roleRsult = UserManager.AddToRole(user.Id, roleName);