当前位置:  开发笔记 > 后端 > 正文

如何使用Identity ASP.NET MVC 6使用代码优先迁移为用户和角色设定种子

如何解决《如何使用IdentityASP.NETMVC6使用代码优先迁移为用户和角色设定种子》经验,为你挑选了2个好方法。

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

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

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

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



1> Muhammad Abd..:

我这样做的方法是在模型名称空间中创建一个类.

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

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

        foreach (string role in roles)
        {
            var roleStore = new RoleStore(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();
            var hashed = password.HashPassword(user,"secret");
            user.PasswordHash = hashed;

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

        }

        AssignRoles(serviceProvider, user.Email, roles);

        context.SaveChangesAsync();
    }

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

        return result;
    }

}

在启动时运行此代码.在配置方法结束时的Startup.cs中,在路由配置之后添加以下代码,如Stafford Williams之前所述.

SampleData.Initialize(app.ApplicationServices);


此代码中几乎没有异步问题(即,不能保证在调用.AddToRolesAsync之前完成userStore.CreateAsync)但概念是最高的

2> Hamid Mosall..:

截至撰写本文时,没有用于播种数据库的插件,但您可以创建一个类并将其添加到容器中以便在应用启动时执行相同的操作,这是我如何完成的,首先是创建一个类:

public class YourDbContextSeedData
{
    private YourDbContext _context;

    public YourDbContextSeedData(YourDbContext context)
    {
        _context = context;
    }

    public async void SeedAdminUser()
    {
        var user = new ApplicationUser
        {
            UserName = "Email@email.com",
            NormalizedUserName = "email@email.com",
            Email = "Email@email.com",
            NormalizedEmail = "email@email.com",
            EmailConfirmed = true,
            LockoutEnabled = false,
            SecurityStamp = Guid.NewGuid().ToString()
        };

        var roleStore = new RoleStore(_context);

        if (!_context.Roles.Any(r => r.Name == "admin"))
        {
            await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });
        }

        if (!_context.Users.Any(u => u.UserName == user.UserName))
        {
            var password = new PasswordHasher();
            var hashed = password.HashPassword(user, "password");
            user.PasswordHash = hashed;
            var userStore = new UserStore(_context);
            await userStore.CreateAsync(user);
            await userStore.AddToRoleAsync(user, "admin");
        }

        await _context.SaveChangesAsync();
    }

在类的ConfigureServices方法中注册类型Startup.cs:

services.AddTransient();

接下来将YourDbContextSeedData类传递给类的Configure方法Startup.cs并使用它:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, YourDbContextSeedData seeder)
{
  seeder.SeedAdminUser();
}

推荐阅读
路人甲
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有