Search code examples
asp.net-mvcasp.net-identityidentityasp.net-identity-2

add role in database in asp mvc identity


i need to when user regiter add in tabel AspNetRole add user id and role id .

but when i create a user show me this error .

enter image description here

how can i insert role in database ?

/*************************************************************************************************/

identityconfig :

 public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
    }
}

public static class SecurityRole
    {
        public const string Admin = "admin";
        public const string Accounting = "accounting";
    }

StartupAuth :

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

AccountController :

public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase IamgeProfile)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Username, Email = model.Email };
            user.Name = model.Name;
            user.Family = model.Family;
            user.Address = model.Address;
            user.BankName = model.BankName;
            user.City = model.City;
            user.Ostan = model.Ostan;
            user.PhoneNumber = model.PhoneNumber;
            user.HomeNumber = model.HomeNumber;
            user.ShabaNo = model.ShabaNo;
            user.PostaCode = model.PostaCode;
            user.NationalCode = model.NationalCode;
            if (IamgeProfile != null)
            {
                IamgeProfile = Request.Files[0];
                var ext = System.IO.Path.GetExtension(IamgeProfile.FileName);
                if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
                {
                    string filename = model.Name + model.Family + model.NationalCode + ext;
                    IamgeProfile.SaveAs(Server.MapPath(@"~/Images/UserImageProfile/" + filename));
                    user.IamgeProfile = filename;
                }
            }
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                await UserManager.AddToRoleAsync(user.Id, role: SecurityRole.Accounting);
                var 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 this link: <a href=\"" + callbackUrl + "\">link</a>");
                ViewBag.Link = callbackUrl;
                return View("DisplayEmail");
            }
            AddErrors(result);
        }

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

Solution

  • To add a role into AspNetRoles you can do this in your Seed() or other startup method:

    if (!context.Roles.Any(r => r.Name == "Admin"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "Admin" };
    
        manager.Create(role);
    }
    

    https://msdn.microsoft.com/en-us/library/dn613057(v=vs.108).aspx