检查用户是否在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后检查时,用户和角色都在数据库中:
谁能看到我做错了什么?
谢谢你的帮助,
标记
我发现了解决方案,以防其他人遇到此问题。
“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")
- 我应该如何从MVC 6视图中访问我的ApplicationUser属性?
- 如何使用Code First在ASP.NET MVC 5 Identity 2.0中的AspNetUser表(Id列)的Customer表(CreatedBy列)中添加外键
- Asp.net核心 – 没有这样的表:AspNetUsers
- ASP.NET Core Identity 3 Cookie超时
- 如何在asp.net mvc身份上设置自定义身份validation?
- 如何在ASP .NET MVC 5中为AspNetUser创建SecurityStamp
- MVC 5:我应该从IdentityUser类inheritance我的用户吗?
- 使用Azure AD时,将用户重定向到自定义登录页面
- 使用ASP.NET Idenity创建默认用户帐户