gpt4 book ai didi

ef-code-first - 如何使用 Identity ASP.NET Core 通过代码优先迁移为用户和角色设定种子

转载 作者:行者123 更新时间:2023-12-03 10:32:22 25 4
gpt4 key购买 nike

我创建了一个新的干净的 asp.net 5 项目 (rc1-final)。使用身份验证,我只拥有带有以下代码的 ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
// On event model creating
base.OnModelCreating(builder);
}
}

请注意 ApplicationDbContext 使用 IdentityDbContext 而不是 DbContext。

有任何 IdentityConfig.cs。如果它不存在,我需要在哪里放置经典的 protected 覆盖​​无效种子来创建角色和用户?

最佳答案

我这样做的方法是在模型命名空间中创建一个类。

public class SampleData
{
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<ApplicationDbContext>();

string[] roles = new string[] { "Owner", "Administrator", "Manager", "Editor", "Buyer", "Business", "Seller", "Subscriber" };

foreach (string role in roles)
{
var roleStore = new RoleStore<IdentityRole>(context);

if (!context.Roles.Any(r => r.Name == role))
{
roleStore.CreateAsync(new IdentityRole(role));
}
}


var user = new ApplicationUser
{
FirstName = "XXXX",
LastName = "XXXX",
Email = "xxxx@example.com",
NormalizedEmail = "XXXX@EXAMPLE.COM",
UserName = "Owner",
NormalizedUserName = "OWNER",
PhoneNumber = "+111111111111",
EmailConfirmed = true,
PhoneNumberConfirmed = true,
SecurityStamp = Guid.NewGuid().ToString("D")
};


if (!context.Users.Any(u => u.UserName == user.UserName))
{
var password = new PasswordHasher<ApplicationUser>();
var hashed = password.HashPassword(user,"secret");
user.PasswordHash = hashed;

var userStore = new UserStore<ApplicationUser>(context);
var result = userStore.CreateAsync(user);

}

AssignRoles(serviceProvider, user.Email, roles);

context.SaveChangesAsync();
}

public static async Task<IdentityResult> AssignRoles(IServiceProvider services, string email, string[] roles)
{
UserManager<ApplicationUser> _userManager = services.GetService<UserManager<ApplicationUser>>();
ApplicationUser user = await _userManager.FindByEmailAsync(email);
var result = await _userManager.AddToRolesAsync(user, roles);

return result;
}

}

在启动时运行此代码。在路由配置之后的配置方法末尾的 Startup.cs 中,添加以下代码,如斯塔福德威廉姆斯之前所说。
SampleData.Initialize(app.ApplicationServices);

关于ef-code-first - 如何使用 Identity ASP.NET Core 通过代码优先迁移为用户和角色设定种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34343599/

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