编程语言
首页 > 编程语言> > c#-将Identity 2.0函数移至存储库类

c#-将Identity 2.0函数移至存储库类

作者:互联网

我正在为我的应用程序使用身份2.0,并希望将数据功能移至存储库层,例如以下代码:

    public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> {
    protected override void Seed(ApplicationDbContext context) {
        InitializeIdentityForEF(context);
        base.Seed(context);
    }

    //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role        
    public static void InitializeIdentityForEF(ApplicationDbContext db) {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();

现在的问题是HttpContext不在存储库层中,您必须将其传递到该层.但是即使这样做,调用也应该来自Web层.但是,您不想在每次对其他图层的调用中都包含userManager.有什么办法吗?

解决方法:

我找到了在存储库层上创建用户管理器的方法:

            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);               
            var user = new ApplicationUser { UserName = "sallen" };

            userManager.Create(user, "password");                    
            roleManager.Create(new IdentityRole { Name = "admin" });
            userManager.AddToRole(user.Id, "admin");

标签:asp-net-mvc-5,asp-net-identity-2,c,entity-framework
来源: https://codeday.me/bug/20191121/2053724.html