Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用MySQL数据库的ASP.NET标识-如何在开始时添加管理员用户?_C#_Mysql_Asp.net_Asp.net Mvc_Asp.net Identity - Fatal编程技术网

C# 使用MySQL数据库的ASP.NET标识-如何在开始时添加管理员用户?

C# 使用MySQL数据库的ASP.NET标识-如何在开始时添加管理员用户?,c#,mysql,asp.net,asp.net-mvc,asp.net-identity,C#,Mysql,Asp.net,Asp.net Mvc,Asp.net Identity,我已经完成了关于如何使用具有ASP.NET标识的MySQL数据库的教程/示例: 现在我想添加一个功能,它可以从角色Admin开始创建Admin用户。过去我使用SimpleMembership和本地“SQL Server数据库”,这非常简单,现在我尝试通过在“MySqlInitializer”中添加用户来实现这一点。下面是我正在努力实现的代码: MySqlInitializer namespace IdentityMySQLDemo { public class MySqlIni

我已经完成了关于如何使用具有ASP.NET标识的MySQL数据库的教程/示例:

现在我想添加一个功能,它可以从角色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);
            }
        }
    }
}
namespace IdentityMySQLDemo
{
公共类MySqlInitializer:IDatabaseInitializer
{
public void InitializeDatabase(ApplicationDbContext上下文)
{
如果(!context.Database.Exists())
{
//如果数据库以前不存在-创建它
context.Database.Create();
}
其他的
{
//查询以检查数据库中是否存在MigrationHistory表
var migrationHistoryTableExists=((IOObjectContextAdapter)上下文)。ObjectContext.ExecuteStoreQuery(
字符串格式(
“从信息_schema.tables中选择COUNT(*),其中表_schema='{0}'和表_name=''uuu MigrationHistory'”,
“17817412_kontadb”);
//如果MigrationHistory表不存在(这是我们第一次运行时的情况)-创建它
if(migrationHistoryTableExists.FirstOrDefault()==0)
{
context.Database.Delete();
context.Database.Create();
}
}
种子(上下文);
}
受保护的空种子(ApplicationDbContext上下文)
{
var userManager=newusermanager(newuserstore(newapplicationdbcontext());
var rolemanger=new rolemanger(new RoleStore(new ApplicationDbContext());
常量字符串名称=”admin@example.com";
const string password=“password”;
常量字符串roleName=“Admin”;
//如果角色Admin不存在,则创建该角色
var role=rolemager.FindByName(roleName);
如果(角色==null)
{
角色=新的识别码(roleName);
var roleresult=rolemanger.Create(角色);
}
var user=userManager.FindByName(名称);
if(user==null)
{
user=newapplicationuser{UserName=name,Email=name};
var result=userManager.Create(用户,密码);
结果=userManager.SetLockoutEnabled(user.Id,false);
}
//将用户管理员添加到角色管理员(如果尚未添加)
var rolesForUser=userManager.GetRoles(user.Id);
如果(!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();
        }
    }
}
使用System.Data.Entity;
使用System.Security.Claims;
使用System.Threading.Tasks;
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.EntityFramework;
名称空间标识mysqldemo.Models
{
//您可以通过向ApplicationUser类添加更多属性来为用户添加配置文件数据,请访问http://go.microsoft.com/fwlink/?LinkID=317594 了解更多。
公共类应用程序用户:IdentityUser
{
公共异步任务GenerateUserIdentityAsync(用户管理器)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
}
公共类ApplicationDbContext:IdentityDbContext
{
静态ApplicationDbContext()
{
SetInitializer(新的MySqlInitializer());
}
公共应用程序上下文()
:base(“DefaultConnection”,throwifvv1schema:false)
{
}
公共静态应用程序上下文创建()
{
返回新的ApplicationDbContext();
}
}
}

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

看起来可能缺少
上下文。SaveChanges()
或三个

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

你还需要打3次电话

  • 创建角色后
  • 创建用户之后
  • 将用户分配给角色后
我自己对C#/ASP.NET MVC比较陌生,所以如果这是正确的修复方法,我也不是100%,因为目前无法测试我的想法,但似乎是我过去遇到过的类似问题

更新

我做了一次尝试,这成功地更新了3个表,作为seed方法的一部分

我认为另一个问题是,与其在几个地方调用一个方法,不如将它们赋给一个变量,然后不使用。例如,在此代码段中:

        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();
    }
protected override void Seed(MySqlInitializer上下文)
{
var userManager=newusermanager(newuserstore(newapplicationdbcontext(“DefaultConnection”));
var roleManager=new roleManager(new RoleStore(new ApplicationDbContext)(“DefaultCon