在 asp mvc identity 数据库中添加角色

add role in database in asp mvc identity

我需要在用户注册时在表格中添加 AspNetRole 添加用户 ID 和角色 ID。

但是当我创建用户时显示此错误。

如何在数据库中插入角色?

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

身份配置:

 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";
    }

启动验证:

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

账户控制器:

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);
    }

要将角色添加到 AspNetRoles 中,您可以在 Seed() 或其他启动方法中执行此操作:

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