Asp.net mvc MVC 5种子用户和角色

Asp.net mvc MVC 5种子用户和角色,asp.net-mvc,asp.net-mvc-5,entity-framework-migrations,seeding,Asp.net Mvc,Asp.net Mvc 5,Entity Framework Migrations,Seeding,我一直在玩新的MVC5,我有一些模型,控制器和视图设置使用代码优先迁移 我的问题是如何为用户和角色播种种子?我目前在Configuration.cs中的seed方法中植入了一些参考数据。但在我看来,直到有东西第一次击中AccountController,用户和角色表才被创建 我目前有两个连接字符串,因此我可以将数据从身份验证分离到不同的数据库中 如何让用户、角色等表与其他表一起填充?而不是当帐户控制器被点击时?看起来他们改变了MVC5中身份验证的工作方式,将my Global.asax.cs更改

我一直在玩新的MVC5,我有一些模型,控制器和视图设置使用代码优先迁移

我的问题是如何为用户和角色播种种子?我目前在Configuration.cs中的seed方法中植入了一些参考数据。但在我看来,直到有东西第一次击中AccountController,用户和角色表才被创建

我目前有两个连接字符串,因此我可以将数据从身份验证分离到不同的数据库中


如何让用户、角色等表与其他表一起填充?而不是当帐户控制器被点击时?

看起来他们改变了MVC5中身份验证的工作方式,将my Global.asax.cs更改为下面的方式完成了这个技巧

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

using System.Threading.Tasks;
using MvcAuth.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Threading;
using Microsoft.AspNet.Identity.EntityFramework;

namespace MvcAuth
{
    public class MvcApplication : System.Web.HttpApplication
    {
        async Task<bool> AddRoleAndUser()
        {
            AuthenticationIdentityManager IdentityManager = new AuthenticationIdentityManager(
                new IdentityStore(new ApplicationDbContext()));

            var role = new Role("Role1");
            IdentityResult result = await IdentityManager.Roles.CreateRoleAsync(role, CancellationToken.None);
            if (result.Success == false)
                return false;

            var user = new ApplicationUser() { UserName = "user1" };
            result = await IdentityManager.Users.CreateLocalUserAsync(user, "Password1");
            if (result.Success == false)
                return false;

            result = await IdentityManager.Roles.AddUserToRoleAsync(user.Id, role.Id, CancellationToken.None);
            return result.Success;
        }

        protected async void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            bool x = await AddRoleAndUser();
        }
    }
}
使用System.Web.Mvc;
使用System.Web.Optimization;
使用System.Web.Routing;
使用System.Threading.Tasks;
使用MvcAuth.Models;
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.Owin;
使用系统线程;
使用Microsoft.AspNet.Identity.EntityFramework;
名称空间MvcAuth
{
公共类MVC应用程序:System.Web.HttpApplication
{
异步任务AddRoleAndUser()
{
AuthenticationIdentityManager IdentityManager=新建AuthenticationIdentityManager(
新的IdentityStore(新的ApplicationDbContext());
var角色=新角色(“角色1”);
IdentityResult结果=等待IdentityManager.Roles.CreateRoleAsync(role,CancellationToken.None);
if(result.Success==false)
返回false;
var user=new ApplicationUser(){UserName=“user1”};
结果=等待IdentityManager.Users.CreateLocalUserAsync(用户,“密码1”);
if(result.Success==false)
返回false;
结果=wait IdentityManager.Roles.AddUserToRoleAsync(user.Id、role.Id、CancellationToken.None);
回报结果。成功;
}
受保护的异步无效应用程序\u Start()
{
RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
bool x=等待AddRoleAndUser();
}
}
}

以下是常用种子方法的示例:

protected override void Seed(SecurityModule.DataContexts.IdentityDb context)
{
    if (!context.Roles.Any(r => r.Name == "AppAdmin"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "AppAdmin" };

        manager.Create(role);
    }

    if (!context.Users.Any(u => u.UserName == "founder"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser {UserName = "founder"};

        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "AppAdmin");
    }
}
protected override void Seed(SecurityModule.DataContexts.IdentityDb context)
{
if(!context.Roles.Any(r=>r.Name==“AppAdmin”))
{
变量存储=新角色存储(上下文);
var经理=新角色经理(门店);
var role=newidentityrole{Name=“AppAdmin”};
创建(角色);
}
如果(!context.Users.Any(u=>u.UserName==“创始人”))
{
var store=新用户存储(上下文);
var-manager=新用户管理器(存储);
var user=newapplicationuser{UserName=“founder”};
创建(用户“ChangeItAsap!”);
manager.AddToRole(user.Id,“AppAdmin”);
}
}

我使用包管理器“更新数据库”。DB和所有表都是用数据创建和播种的。

这是一个小的添加,但对于任何拥有“未找到用户ID”的人来说。尝试播种时的消息:(Tom Regan在评论中提出了这个问题,我自己也被困了一段时间)

这意味着manager.Create(用户“ChangeItAsap!”)未成功。 这可能有不同的原因,但对我来说,这是因为我的密码没有通过验证


我有一个自定义passwordvalidator,在为数据库设定种子时没有调用它,因此我使用的验证规则(minlength 4而不是默认的6)不适用。确保您的密码(以及与此相关的所有其他字段)通过验证。

这是我基于Valin answer的方法,我在db中添加了角色,并为用户添加了密码。此代码位于Migrations>Configurations.cs中的
Seed()
方法中

// role (Const.getRoles() return string[] whit all roles)

    var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    for (int i = 0; i < Const.getRoles().Length; i++)
    {
        if (RoleManager.RoleExists(Const.getRoles()[i]) == false)
        {
            RoleManager.Create(new IdentityRole(Const.getRoles()[i]));
        }
    }

// user

    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    var PasswordHash = new PasswordHasher();
    if (!context.Users.Any(u => u.UserName == "admin@admin.net"))
    {
        var user = new ApplicationUser
        {
             UserName = "admin@admin.net",
             Email = "admin@admin.net",
             PasswordHash = PasswordHash.HashPassword("123456")
         };

         UserManager.Create(user);
         UserManager.AddToRole(user.Id, Const.getRoles()[0]);
    }
//角色(Const.getRoles()返回字符串[],其中包含所有角色)
var角色管理器=新角色管理器(新角色存储(上下文));
for(int i=0;iu.UserName==)admin@admin.net"))
{
var user=新应用程序用户
{
用户名=”admin@admin.net",
电子邮件=”admin@admin.net",
PasswordHash=PasswordHash.HashPassword(“123456”)
};
UserManager.Create(用户);
UserManager.AddToRole(user.Id,Const.getRoles()[0]);
}
受保护的覆盖无效种子(ApplicationDbContext上下文)
{
SeedAsync(context.GetAwaiter().GetResult();
}
专用异步任务SeedAsync(ApplicationDbContext上下文)
{
var userManager=newapplicationUserManager(newuserstore(context));
var rolemanger=新应用程序rolemanger(新角色存储(上下文));
如果(!roleManager.Roles.Any())
{
等待roleManager.CreateAsync(新的ApplicationRole{Name=ApplicationRole.AdminRoleName});
等待roleManager.CreateAsync(新的ApplicationRole{Name=ApplicationRole.AffiliateRoleName});
}
如果(!userManager.Users.Any(u=>u.UserName==“shimmy”))
{
var user=新应用程序用户
{
UserName=“shimmy”,
电子邮件=”shimmy@gmail.com",
emailconfirm=true,
PhoneNumber=“0123456789”,
phonenumberconfirm=true
};
等待userManager.CreateAsync(用户,*****);
等待userManager.AddToRoleAsync(user.Id,ApplicationRole.AdminRoleName);
}
}

这里我有一个非常简单、干净、光滑的解决方案

 protected override void Seed(UserContext context)
    { 
        //Step 1 Create the user.
        var passwordHasher = new PasswordHasher();
        var user = new IdentityUser("Administrator");
        user.PasswordHash = passwordHasher.HashPassword("Admin12345");
        user.SecurityStamp = Guid.NewGuid().ToString();

        //Step 2 Create and add the new Role.
        var roleToChoose = new IdentityRole("Admin");
        context.Roles.Add(roleToChoose);

        //Step 3 Create a role for a user
        var role = new IdentityUserRole();
        role.RoleId = roleToChoose.Id;
        role.UserId = user.Id;

         //Step 4 Add the role row and add the user to DB)
        user.Roles.Add(role);
        context.Users.Add(user);
    }

在迁移配置中编写此代码

注意:在配置类中使用ApplicationDbContext

内海
 protected override void Seed(UserContext context)
    { 
        //Step 1 Create the user.
        var passwordHasher = new PasswordHasher();
        var user = new IdentityUser("Administrator");
        user.PasswordHash = passwordHasher.HashPassword("Admin12345");
        user.SecurityStamp = Guid.NewGuid().ToString();

        //Step 2 Create and add the new Role.
        var roleToChoose = new IdentityRole("Admin");
        context.Roles.Add(roleToChoose);

        //Step 3 Create a role for a user
        var role = new IdentityUserRole();
        role.RoleId = roleToChoose.Id;
        role.UserId = user.Id;

         //Step 4 Add the role row and add the user to DB)
        user.Roles.Add(role);
        context.Users.Add(user);
    }
    internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data.
                   context.Roles.AddOrUpdate(p =>
            p.Id,
                new IdentityRole { Name = "Admins"},
                new IdentityRole { Name = "PowerUsers" },
                new IdentityRole { Name = "Users" },
                new IdentityRole { Name = "Anonymous" }
            );


    }
}