ASP.如何在开始时添加Admin用户
本文关键字:添加 Admin 用户 开始时 ASP | 更新日期: 2023-09-27 18:08:32
我已经完成了这个教程/样本,关于如何使用MySQL数据库与ASP。NET身份:
http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
现在我想添加功能,创建Admin用户与角色Admin开始。在过去,我使用simplembermembership和本地"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);
}
}
}
}
IdentityModels
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用户,我试图将此代码移动到迁移文件夹中的"配置"或"MySQLConfiguration"。我还试图首先创建所有表,然后添加Admin用户,但它仍然不起作用。请告诉我在这个代码中我愚蠢的错误在哪里?
看起来可能缺少一个或三个context.SaveChanges()
。
你的种子方法有问题吗?如果问题是当你在NuGet包管理器控制台运行update-database
命令时,如果没有对context.SaveChanges()
的调用,那么它将不会更新DB。
你还需要调用它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();
}
在某些方面,我想感谢你,因为帮助了你,我也帮助了自己。