gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:11:50 27 4
gpt4 key购买 nike

我正在为我的应用程序使用 identity 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");

关于c# - 将 Identity 2.0 函数移动到存储库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23861196/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com