检查用户是否在asp.net mvc Identity中扮演角色

我在使用用户和角色为数据库播种时遇到了问题。

创建了用户和角色(我可以在抛出错误后在数据库中看到它们)。

但是,当我尝试检查用户是否在角色中时,我得到一个例外。

我的代码是:

public class tbInitializer : DropCreateDatabaseAlways { protected override void Seed(tbContext context) { ApplicationDbContext userscontext = new ApplicationDbContext(); var userStore = new UserStore(userscontext); var userManager = new UserManager(userStore); var roleStore = new RoleStore(userscontext); var roleManager = new RoleManager(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"); } 

但是,在线:

if(!userManager.IsInRole("marktest","Admin"))

引发错误的exception: UserId not found.

在抛出exception后检查时,用户和角色都在数据库中:

显示添加到DB的用户

显示添加到DB的角色

谁能看到我做错了什么?

谢谢你的帮助,

标记

我发现了解决方案,以防其他人遇到此问题。

“IsInRole”期待User.Id – 而不是UserName字符串 – 所以我改为:

  if (!userManager.IsInRole(user.Id, "Admin")) { userManager.AddToRole(user.Id, "Admin"); } 

所以工作代码变成:

  ApplicationDbContext userscontext = new ApplicationDbContext(); var userStore = new UserStore(userscontext); var userManager = new UserManager(userStore); var roleStore = new RoleStore(userscontext); var roleManager = new RoleManager(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"); } } 

我希望有帮助,

标记

生活中最简单的事情;

 bool isAdmin= User.IsInRole("admin")