如何使用 Identity ASP.NET Core 通过代码优先迁移为用户和角色播种 [英] How to Seed Users and Roles with Code First Migration using Identity ASP.NET Core

查看:17
本文介绍了如何使用 Identity ASP.NET Core 通过代码优先迁移为用户和角色播种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的干净的 asp.net 5 项目(rc1-final).使用身份验证我只有 ApplicationDbContext.cs 和以下代码:

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);
    }
}

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

Please note ApplicationDbContext use IdentityDbContext and not DbContext.

有任何 IdentityConfig.cs.如果不存在,我需要将经典受保护的覆盖无效种子放在哪里来创建角色和用户?

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 = "XXXX",
            LastName = "XXXX",
            Email = "xxxx@example.com",
            NormalizedEmail = "XXXX@EXAMPLE.COM",
            UserName = "Owner",
            NormalizedUserName = "OWNER",
            PhoneNumber = "+111111111111",
            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 之前所说.

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);

这篇关于如何使用 Identity ASP.NET Core 通过代码优先迁移为用户和角色播种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆