且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过使用身份识别ASP.NET MVC的代码首次迁移来种子用户和角色6

更新时间:2023-02-25 23:39:55

我的方式这样做是在模型命名空间中创建一个类。

  public class SampleData 
{
public static void初始化(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService< ApplicationDbContext>();

string [] roles = new string [] {Owner,Administrator,Manager,Editor,Buyer,Business,Seller,Subscriber ;

foreach(角色角色中的角色)
{
var roleStore = new RoleStore< IdentityRole>(context);

if(!context.Roles.Any(r => r.Name == role))
{
roleStore.CreateAsync(new IdentityRole(role));
}
}


var user = new ApplicationUser
{
FirstName =Muhammad,
LastName =Abdullah ,
Email =abdullahnaseer999@gmail.com,
NormalizedEmail =ABDULLAHNASEER999@GMAIL.COM,
UserName =Owner,
NormalizedUserName =OWNER
PhoneNumber =+923366633352,
EmailConfirmed = true,
PhoneNumberConfirmed = true,
SecurityStamp = Guid.NewGuid()。ToString(D)
} ;


if(!context.Users.Any(u => u.UserName == user.UserName))
{
var password = new PasswordHasher< ApplicationUser&GT;();
var hashed = password.HashPassword(user,secret);
user.PasswordHash = hashed;

var userStore = new UserStore< ApplicationUser>(context);
var result = userStore.CreateAsync(user);

}

AssignRoles(serviceProvider,user.Email,roles);

context.SaveChangesAsync();
}

public static async任务< IdentityResult> AssignRoles(IServiceProvider services,string email,string [] roles)
{
UserManager< ApplicationUser> _userManager = services.GetService< UserManager< ApplicationUser>>();
ApplicationUser user = await _userManager.FindByEmailAsync(email);
var result = await _userManager.AddToRolesAsync(user,roles);

返回结果;
}

}

启动时运行此代码。在配置方法结束后的Startup.cs中,路由配置后添加以下代码作为Stafford Williams说。

  SampleData.Initialize app.ApplicationServices); 


I have created a new clean asp.net 5 project (rc1-final). Using Identity Authentication I just have the ApplicationDbContext.cs with the following code:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        // On event model creating
        base.OnModelCreating(builder);
    }
}

Please note ApplicationDbContext use IdentityDbContext and not DbContext.

There is any IdentityConfig.cs. Where i need to put the classic protected override void Seed to create role and user if it does not exist?

My way of doing this is to create a class in models namespace.

public class SampleData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        var context = serviceProvider.GetService<ApplicationDbContext>();

        string[] roles = new string[] { "Owner", "Administrator", "Manager", "Editor", "Buyer", "Business", "Seller", "Subscriber" };

        foreach (string role in roles)
        {
            var roleStore = new RoleStore<IdentityRole>(context);

            if (!context.Roles.Any(r => r.Name == role))
            {
                roleStore.CreateAsync(new IdentityRole(role));
            }
        }


        var user = new ApplicationUser
        {
            FirstName = "Muhammad",
            LastName = "Abdullah",
            Email = "abdullahnaseer999@gmail.com",
            NormalizedEmail = "ABDULLAHNASEER999@GMAIL.COM",
            UserName = "Owner",
            NormalizedUserName = "OWNER",
            PhoneNumber = "+923366633352",
            EmailConfirmed = true,
            PhoneNumberConfirmed = true,
            SecurityStamp = Guid.NewGuid().ToString("D")
        };


        if (!context.Users.Any(u => u.UserName == user.UserName))
        {
            var password = new PasswordHasher<ApplicationUser>();
            var hashed = password.HashPassword(user,"secret");
            user.PasswordHash = hashed;

            var userStore = new UserStore<ApplicationUser>(context);
            var result = userStore.CreateAsync(user);

        }

        AssignRoles(serviceProvider, user.Email, roles);

        context.SaveChangesAsync();
    }

    public static async Task<IdentityResult> AssignRoles(IServiceProvider services, string email, string[] roles)
    {
        UserManager<ApplicationUser> _userManager = services.GetService<UserManager<ApplicationUser>>();
        ApplicationUser user = await _userManager.FindByEmailAsync(email);
        var result = await _userManager.AddToRolesAsync(user, roles);

        return result;
    }

}

To run this code on startup. In Startup.cs at end of configure method just after route configuration add following code as Stafford Williams said before.

SampleData.Initialize(app.ApplicationServices);