如何通过使用身份识别ASP.NET MVC的代码首次迁移来种子用户和角色6 [英] How to Seed Users and Roles with Code First Migration using Identity ASP.NET MVC 6

查看:156
本文介绍了如何通过使用身份识别ASP.NET MVC的代码首次迁移来种子用户和角色6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个新的干净的asp.net 5项目(rc1-final)。使用身份认证我只是使用ApplicationDbContext.cs与以下代码:

  public class ApplicationDbContext:IdentityDbContext< ApplicationUser> 
{
protected override void OnModelCreating(ModelBuilder builder)
{
//在事件模型创建
base.OnModelCreating(builder);
}
}

请注意ApplicationDbContext使用IdentityDbContext而不是DbContext。 p>

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

解决方案

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

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

这篇关于如何通过使用身份识别ASP.NET MVC的代码首次迁移来种子用户和角色6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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