使用ASP.NET Idenity创建默认用户帐户

时间:2013-10-27 06:53:08

标签: c# asp.net asp.net-mvc asp.net-identity

我正在使用ASP.NET MVC 5和Identity API开发一个简单的应用程序。我想问一下,在创建表和启动应用程序时,如何在超级管理员角色中创建超级管理员帐户。我使用默认的ASP.NET MVC 5与Visual Studio 2013的个人帐户模板,我不知道如何做我的目标。

2 个答案:

答案 0 :(得分:4)

没关系,我发现这个有用的链接可以准确显示我想要的内容:

https://github.com/rustd/AspnetIdentitySample/blob/master/AspnetIdentitySample/App_Start/IdentityConfig.cs

答案 1 :(得分:0)

我在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!
    }
}