Create a default user account using ASP.NET Idenit

2019-05-16 23:44发布

问题:

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.

回答1:

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



回答2:

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