【问题标题】:ASP.NET Identity with MySQL database - How to add Admin user on start?带有 MySQL 数据库的 ASP.NET 身份 - 如何在启动时添加管理员用户?
【发布时间】:2015-11-12 03:02:12
【问题描述】:

我已经完成了本教程/示例,关于如何使用带有 ASP.NET 身份的 MySQL 数据库:
http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
现在我想添加功能,以管理员角色开始创建管理员用户。过去我使用 SimpleMembership 和本地“SQL Server 数据库”,这很简单,现在我试图通过在“MySqlInitializer”中添加用户来做到这一点。这是我正在尝试制作的代码:

MySqlInitializer

    namespace IdentityMySQLDemo
{
    public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
    {
        public void InitializeDatabase(ApplicationDbContext context)
        {
            if (!context.Database.Exists())
            {
                // if database did not exist before - create it
                context.Database.Create();
            }
            else
            {
                // query to check if MigrationHistory table is present in the database 
                var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
                string.Format(
                  "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
                  "17817412_kontadb"));

                // if MigrationHistory table is not there (which is the case first time we run) - create it
                if (migrationHistoryTableExists.FirstOrDefault() == 0)
                {
                    context.Database.Delete();
                    context.Database.Create();
                }
            }
            Seed(context);
        }

        protected void Seed(ApplicationDbContext context)
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            const string name = "admin@example.com";
            const string password = "Password";
            const string roleName = "Admin";

            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);
            if (role == null)
            {
                role = new IdentityRole(roleName);
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }
        }
    }
}

身份模型

using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace IdentityMySQLDemo.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        static ApplicationDbContext()
        {
          Database.SetInitializer(new MySqlInitializer());
        }

        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

我不知道为什么它不想在应用程序启动时创建管理员用户,我试图将此代码移动到 Migrations 文件夹中的“配置”或“MySQLConfiguration”。我还尝试先创建所有表而不是用这个添加管理员用户,但它仍然没有工作。请告诉我这段代码中我的愚蠢错误在哪里?

【问题讨论】:

  • 是在创建角色和用户吗?
  • 当我通过网站注册新用户时,它会在数据库和新用户中创建所有表(没有管理员用户),但是当我启动应用程序时,数据库是空的,没有表并且没有管理员用户。我知道连接很好,我可以创建用户,但启动时什么也没有。

标签: c# mysql asp.net asp.net-mvc asp.net-identity


【解决方案1】:

看起来可能缺少一个 context.SaveChanges() 或三个。

是你的种子方法有问题吗?如果问题是当您在 NuGet 包管理器控制台中运行 update-database 命令时,如果没有调用 context.SaveChanges(),则它不会更新数据库。

你还需要调用它 3 次..

  • 角色创建后
  • 用户创建后
  • 用户被分配到角色之后

我自己是 C# / ASP.NET MVC 的新手,所以如果这是正确的解决方法,我不是 100%,因为目前无法测试我的想法,但似乎是我过去遇到过的类似问题.

更新

我玩过,作为种子方法的一部分,这成功更新了 3 个表。

我认为其他问题之一是,您不是在几个地方调用一个方法,而是将它们分配给一个变量,然后不使用。例如在这个 sn-p 中:

        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name))
        {
            var result = userManager.AddToRole(user.Id, role.Name);
        }

我改成:

        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name))
        {
            userManager.AddToRole(user.Id, role.Name);
        }

因此删除 var result =

这里是完整的代码:

    protected override void Seed( MySqlInitializer context)
    {
        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext("DefaultConnection")));
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext("DefaultConnection")));
        const string name = "admin@example.com";
        const string password = "Password";
        const string roleName = "Admin";

        //Create Role Admin if it does not exist
        var role = roleManager.FindByName(roleName);
        if (role == null)
        {
            role = new IdentityRole(roleName);
            roleManager.Create(role);
        }
        context.SaveChanges();
        var user = userManager.FindByName(name);
        if (user == null)
        {
            user = new ApplicationUser { UserName = name, Email = name };
            userManager.Create(user, password);
            userManager.SetLockoutEnabled(user.Id, false);
        }
        context.SaveChanges();
        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name))
        {
            userManager.AddToRole(user.Id, role.Name);
        }
        context.SaveChanges();
    }

在某些方面我要感谢你,因为我帮助了你,我帮助了自己:)

【讨论】:

    猜你喜欢
    • 2013-08-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多