【问题标题】:add role in database in asp mvc identity在 asp mvc 身份中的数据库中添加角色
【发布时间】:2016-10-17 16:54:29
【问题描述】:

当用户注册时我需要在表中添加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);
    }

【问题讨论】:

    标签: asp.net-mvc asp.net-identity identity asp.net-identity-2


    【解决方案1】:

    要将角色添加到 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

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 2018-08-26
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2013-08-19
      • 2016-01-14
      相关资源
      最近更新 更多