简体   繁体   中英

Create a default user account using ASP.NET Idenity

I am developing a simple application using ASP.NET MVC 5 and the Identity API. I would like to ask how I am able to create a Super Administrator account inside a Super Administrators role upon creation of the tables and startup of the application. I am using the default ASP.NET MVC 5 with Individual Accounts template of Visual Studio 2013 and I am not sure how to do what I aim.

Never mind, I found this useful link that shows exactly what I want:

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

I do it inside of seed() method of Configuration class like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM