使用ASP.NET Identity创建默认用户帐户
本文关键字:用户 默认 创建 ASP NET Identity 使用 | 更新日期: 2023-09-27 18:37:03
我正在使用ASP.NET MVC 5和Identity API开发一个简单的应用程序。我想问一下,在创建表和启动应用程序时,我如何能够在超级管理员角色中创建超级管理员帐户。我使用的是Visual Studio 2013的默认ASP.NET MVC 5 with Individual Accounts模板,我不知道如何实现我的目标。
没关系,我发现了这个有用的链接,它正好显示了我想要的东西:
https://github.com/rustd/AspnetIdentitySample/blob/master/AspnetIdentitySample/App_Start/IdentityConfig.cs
我在Configuration
类的seed()
方法中这样做:
protected override void Seed(AuthContext context)
{
const string userName = "AdminUserName";
const string password = "AdminPassword";
const string roleName = "AdminRole";
const string phoneNumber = "PhoneNumber";
var appUserStore = new UserStore<ApplicationUser>(context);
var appUserManager = new UserManager<ApplicationUser>(appUserStore);
var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context));
try
{
var user = context.Users.SingleOrDefault(u => u.UserName == userName);
var role = context.Roles.SingleOrDefault(r => r.Name == roleName);
if (role == null)
{
appRoleManager.CreateAsync(new IdentityRole(roleName)).Wait();
role = context.Roles.SingleOrDefault(r => r.Name == roleName);
}
if (user == null)
{
appUserManager.CreateAsync(new ApplicationUser { UserName = userName, PhoneNumber = phoneNumber}, password).Wait();
user = context.Users.SingleOrDefault(u => u.UserName == nationalCode);
}
var userRole = user.Roles.SingleOrDefault(r => r.RoleId == role.Id);
if (userRole == null)
{
appUserManager.AddToRoleAsync(user.Id, roleName).Wait();
}
}
catch (Exception ex)
{
// Error catched!
}
}