数据库
首页 > 数据库> > 带有MySQL数据库的ASP.NET身份-如何在启动时添加Admin用户?

带有MySQL数据库的ASP.NET身份-如何在启动时添加Admin用户?

作者:互联网

我已经完成了有关如何使用具有ASP.NET标识的MySQL数据库的本教程/示例:
http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
现在,我想添加功能,以角色Admin开头创建Admin用户.过去,我使用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();
        }
    }
}

我不知道为什么它不想在应用程序启动时创建Admin用户,我试图将这段代码移到Migrations文件夹中的“ Configuration”或“ MySQLConfiguration”中,我还试图首先创建所有表,然后添加管理员用户使用此功能,但仍然无法使用,请告诉我这段代码的愚蠢错误在哪里?

解决方法:

看起来好像缺少上下文了.SaveChanges()或三个.

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

您还需要调用3次.

>创建角色后
>创建用户后
>将用户分配给角色后

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

更新

我玩了一圈,这成功地将3个表更新为种子方法的一部分.

我认为另一个问题是,您没有在几个地方调用方法,而是只是将它们分配给变量,然后不使用.例如在以下代码段中:

        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结果=

这是完整的代码:

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

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

标签:asp-net-identity,asp-net,c,asp-net-mvc,mysql
来源: https://codeday.me/bug/20191119/2039352.html