我正在尝试在MVC 5中启动应用程序时创建root用户。
我尝试在IdentityConfig.cs中添加一个调用种子方法的类。另外,我在某个地方读到可以在startup.cs上运行它,但是在任何地方都找不到该链接。
public class RootInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
string Email = "root@root.com";
string UserName = "root";
string Password = "root";
string FullName = "root";
string Role = "Root";
if (!RoleManager.RoleExists(Role))
{
var RoleResult = RoleManager.Create(new IdentityRole(Role));
}
var User = new ApplicationUser();
User.Email = Email;
User.UserName = UserName;
User.FullName = FullName;
if (UserManager.Create(User, Password).Succeeded)
{
UserManager.AddToRole(User.Id, Role);
}
base.Seed(context);
}
}
更新:我在本教程中找到了解决方案。 https://jorgeramon.me/2015/how-to-seed-users-and-roles-in-an-asp-net-mvc-application/