MVC 5种子用户和angular色

我一直在玩新的MVC 5,我有几个模型,控制器和视图设置使用代码第一次迁移。

我的问题是如何种子用户和angular色? 我目前在Configuration.cs的种子方法中种下一些参考数据。 但是,在我看来,用户和angular色表不会创build,直到第一次触及AccountController。

我目前有两个连接string,所以我可以将我的数据从我的身份validation分为不同的数据库。

我怎么能得到用户,angular色等表填充与我的其他人? 而不是当帐户控制器被击中?

这里是通常的种子方法的例子:

protected override void Seed(SecurityModule.DataContexts.IdentityDb context) { if (!context.Roles.Any(r => r.Name == "AppAdmin")) { var store = new RoleStore<IdentityRole>(context); var manager = new RoleManager<IdentityRole>(store); var role = new IdentityRole { Name = "AppAdmin" }; manager.Create(role); } if (!context.Users.Any(u => u.UserName == "founder")) { var store = new UserStore<ApplicationUser>(context); var manager = new UserManager<ApplicationUser>(store); var user = new ApplicationUser {UserName = "founder"}; manager.Create(user, "ChangeItAsap!"); manager.AddToRole(user.Id, "AppAdmin"); } } 

我使用包pipe理器“更新数据库”。 数据库和所有表格创build和播种数据。

这是我的方法基于华菱的答案,我已经在数据库中添加angular色,并为用户添encryption码。 此代码放置在Migrations> Configurations.cs中的Seed()方法中。

 // role (Const.getRoles() return string[] whit all roles) var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); for (int i = 0; i < Const.getRoles().Length; i++) { if (RoleManager.RoleExists(Const.getRoles()[i]) == false) { RoleManager.Create(new IdentityRole(Const.getRoles()[i])); } } // user var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var PasswordHash = new PasswordHasher(); if (!context.Users.Any(u => u.UserName == "admin@admin.net")) { var user = new ApplicationUser { UserName = "admin@admin.net", Email = "admin@admin.net", PasswordHash = PasswordHash.HashPassword("123456") }; UserManager.Create(user); UserManager.AddToRole(user.Id, Const.getRoles()[0]); } 

这是一个小的补充,但对任何人都有“UserId找不到”。 试图播种时的消息:(汤姆·里根在评论中有这个问题,而且我自己也被困住了一会儿)

这意味着manager.Create(用户,“ChangeItAsap!”)不成功。 这可能有不同的原因,但对我来说是因为我的密码没有成功validation。

我有一个自定义的密码validation器,在种子数据库时没有被调用,所以我使用的validation规则(最小长度4而不是默认值6)不适用。 确保你的密码(和其他所有的领域)通过validation。

我所做的是创build另一个asynchronous方法,并同步调用它,对我来说是完美的。

 protected override void Seed(ApplicationDbContext context) { Task.Run(async () => { await SeedAsync(context); }).Wait(); } private async Task SeedAsync(ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context)); var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole, int, ApplicationUserRole>(context)); if (!roleManager.Roles.Any()) { await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AdminRoleName }); await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AffiliateRoleName }); } if (!userManager.Users.Any(u => u.UserName == "shimmy")) { var user = new ApplicationUser { UserName = "shimmy", Email = "shimmy@gmail.com", EmailConfirmed = true, PhoneNumber = "0123456789", PhoneNumberConfirmed = true }; await userManager.CreateAsync(user, "****"); await userManager.AddToRoleAsync(user.Id, ApplicationRole.AdminRoleName); } } 

看起来他们改变了身份validation在MVC5中的工作方式,改变了我的Global.asax.cs到下面的伎俩!

 using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Threading.Tasks; using MvcAuth.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using System.Threading; using Microsoft.AspNet.Identity.EntityFramework; namespace MvcAuth { public class MvcApplication : System.Web.HttpApplication { async Task<bool> AddRoleAndUser() { AuthenticationIdentityManager IdentityManager = new AuthenticationIdentityManager( new IdentityStore(new ApplicationDbContext())); var role = new Role("Role1"); IdentityResult result = await IdentityManager.Roles.CreateRoleAsync(role, CancellationToken.None); if (result.Success == false) return false; var user = new ApplicationUser() { UserName = "user1" }; result = await IdentityManager.Users.CreateLocalUserAsync(user, "Password1"); if (result.Success == false) return false; result = await IdentityManager.Roles.AddUserToRoleAsync(user.Id, role.Id, CancellationToken.None); return result.Success; } protected async void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); bool x = await AddRoleAndUser(); } } } 

在这里,我有一个非常简单,干净,顺利的解决scheme。

  protected override void Seed(UserContext context) { //Step 1 Create the user. var passwordHasher = new PasswordHasher(); var user = new IdentityUser("Administrator"); user.PasswordHash = passwordHasher.HashPassword("Admin12345"); user.SecurityStamp = Guid.NewGuid().ToString(); //Step 2 Create and add the new Role. var roleToChoose = new IdentityRole("Admin"); context.Roles.Add(roleToChoose); //Step 3 Create a role for a user var role = new IdentityUserRole(); role.RoleId = roleToChoose.Id; role.UserId = user.Id; //Step 4 Add the role row and add the user to DB) user.Roles.Add(role); context.Users.Add(user); }