我正在使用 ASP.NET MVC 5 和 Identity API 开发一个简单的应用程序。我想问一下如何在创建表和启动应用程序时在超级管理员角色中创建超级管理员帐户。我正在使用默认的 ASP.NET MVC 5 和 Visual Studio 2013 的个人帐户模板,我不知道如何做我的目标。
问问题
9847 次
2 回答
5
没关系,我发现这个有用的链接准确地显示了我想要的内容:
于 2013-10-27T07:00:22.013 回答
1
我在类的seed()
方法中Configuration
这样做:
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!
}
}
于 2016-07-21T15:34:19.500 回答