Mar*_*ark 13 c# asp.net-mvc asp.net-mvc-4 asp.net-identity
我在使用用户和角色为数据库播种时遇到了问题.
创建用户和角色(我可以在抛出错误后在数据库中看到它们).
但是,当我尝试检查用户是否在角色中时,我得到一个例外.
我的代码是:
public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext>
{
protected override void Seed(tbContext context)
{
ApplicationDbContext userscontext = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(userscontext);
var userManager = new UserManager<ApplicationUser>(userStore);
var roleStore = new RoleStore<IdentityRole>(userscontext);
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
{
var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" };
userManager.Create(user, "Pa$$W0rD!");
}
if (!roleManager.RoleExists("Admin"))
{
roleManager.Create(new IdentityRole("Admin"));
}
if(!userManager.IsInRole("marktest","Admin"))
{
userManager.AddToRole("marktest","Admin");
}
Run Code Online (Sandbox Code Playgroud)
但是,在线:
if(!userManager.IsInRole("marktest","Admin"))
抛出错误的异常: UserId not found.
在抛出异常后检查时,用户和角色都在数据库中:
谁能看到我做错了什么?
谢谢你的帮助,
标记
Mar*_*ark 26
我找到了解决方案,以防其他人遇到此问题.
"IsInRole"期待User.Id - 而不是UserName字符串 - 所以我改为:
if (!userManager.IsInRole(user.Id, "Admin"))
{
userManager.AddToRole(user.Id, "Admin");
}
Run Code Online (Sandbox Code Playgroud)
所以工作代码变成:
ApplicationDbContext userscontext = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(userscontext);
var userManager = new UserManager<ApplicationUser>(userStore);
var roleStore = new RoleStore<IdentityRole>(userscontext);
var roleManager = new RoleManager<IdentityRole>(roleStore);
// Create Role
if (!roleManager.RoleExists("Admin"))
{
roleManager.Create(new IdentityRole("Admin"));
}
if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
{
// Create User
var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" };
userManager.Create(user, "Pa$$W0rD!");
// Add User To Role
if (!userManager.IsInRole(user.Id, "Admin"))
{
userManager.AddToRole(user.Id, "Admin");
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有帮助,
标记
归档时间: |
|
查看次数: |
30434 次 |
最近记录: |