在 Migrations Configuration 类中,有 Seed 方法,它看起来像:
protected override void Seed(DatabaseContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<User>(new UserStore<User>(context));
if (!roleManager.RoleExists("Administrator"))
{
roleManager.Create(new IdentityRole("Administrator"));
}
var user = new User {UserName = "someUserName"};
if (userManager.FindByName("someUserName") == null)
{
var result = userManager.Create(user, "password");
if (result.Succeeded)
{
userManager.AddToRole(user.Id, "Administrator");
}
}
}
然后在 PM 控制台中,我运行了 update-database,它成功地播种了数据库,在表 AspNetUserRoles 中,我可以看到用户 someUserName 和管理员角色已连接。
但是当我把属性
[Authorize(Roles = "Administrator")]
在 Controller 上方,我已被重定向到登录页面,就好像我的用户不在该角色中一样,因此我在 Controller 中添加了一行:var x = _userManager.IsInRole(_userManager.FindByName("someUserName").Id, "Administrator");
而 x 是假的。为什么会这样?我该如何解决?如果这不是种子数据库的正确方法,哪个是?
最佳答案
试试你的种子方法
context.Configuration.LazyLoadingEnabled = true;
这是我对禁用延迟加载时发生的情况的猜测,
IdentityUser
的 Roles 属性/ApplicationUser
当 UserManager 或 UserStore 访问它时,对象为 null 或空,因为该集合不是手动加载的。然后代码继续执行,就像没有为用户分配角色一样,而实际上该集合从未加载过。
关于ASP.net MVC + ASP.net Identity Seeding 角色和用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20470623/