ef-code-first – 如何通过使用Identity ASP.NET MVC的代码优先迁移来种子用户和角色6

前端之家收集整理的这篇文章主要介绍了ef-code-first – 如何通过使用Identity ASP.NET MVC的代码优先迁移来种子用户和角色6前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经创建了一个新的干净的asp.net 5项目(rc1-final).使用身份认证我只需要ApplicationDbContext.cs与以下代码
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        // On event model creating
        base.OnModelCreating(builder);
    }
}

请注意ApplicationDbContext使用IdentityDbContext而不是DbContext.

有任何IdentityConfig.cs.我需要把经典的保护覆盖void Seed来创建角色和用户,如果它不存在?

解决方法

我这样做的方法是在模型命名空间中创建一个类.
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;
    }

}

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

SampleData.Initialize(app.ApplicationServices);
原文链接:https://www.f2er.com/aspnet/246531.html

猜你在找的asp.Net相关文章