我正在制作一个简单的小型web应用程序项目来更好地学习,并使用带有身份的asp.net核心6.0mvc,我有两个角色,管理和用户。我想给管理员一个阻止用户的可能性。为此,我知道我必须创造第三个角色,但由于我仍然是个初学者,我不知道下一步该做什么。我发现了许多类似于这个https://csharp-video-tutorials.blogspot.com/2019/07/add-or-remove-users-from-role-in-aspnet.html的教程,但它们都有一些我无法访问的共同之处,userManager。示例
[HttpGet]
public async Task<IActionResult> EditUsersInRole(string roleId)
{
ViewBag.roleId = roleId;
var role = await roleManager.FindByIdAsync(roleId);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {roleId} cannot be found";
return View("NotFound");
}
var model = new List<UserRoleViewModel>();
foreach (var user in userManager.Users)
{
var userRoleViewModel = new UserRoleViewModel
{
UserId = user.Id,
UserName = user.UserName
};
if (await userManager.IsInRoleAsync(user, role.Name))
{
userRoleViewModel.IsSelected = true;
}
else
{
userRoleViewModel.IsSelected = false;
}
model.Add(userRoleViewModel);
}
return View(model);
}userManager.Users给出一个错误“名称'userManager‘在当前上下文中不存在”,roleManager.FindByIdAsync也给出了相同的错误
我使用的是ApplicationUser类
public class ApplicationUser : IdentityUser
{
public virtual Profile? Profile { get; set; }
}ApplicationDbContext是
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext() {}
public DbSet<Profile> Profiles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connection = @"Server=(localdb)\mssqllocaldb;Database=ExerciseDb; Trusted_Connection=True;";
optionsBuilder.UseLazyLoadingProxies().UseSqlServer(connection);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.HasDefaultSchema("Identity");
builder.Entity<IdentityUser>(entity =>
{
entity.ToTable(name: "User");
});
builder.Entity<IdentityRole>(entity =>
{
entity.ToTable(name: "Role");
});
builder.Entity<IdentityUserRole<string>>(entity =>
{
entity.ToTable("UserRoles");
});
builder.Entity<IdentityUserClaim<string>>(entity =>
{
entity.ToTable("UserClaims");
});
builder.Entity<IdentityUserLogin<string>>(entity =>
{
entity.ToTable("UserLogins");
});
builder.Entity<IdentityRoleClaim<string>>(entity =>
{
entity.ToTable("RoleClaims");
});
builder.Entity<IdentityUserToken<string>>(entity =>
{
entity.ToTable("UserTokens");
});
builder.Entity<ApplicationUser>()
.HasOne(a => a.Profile)
.WithOne(p => p.ApplicationUser)
.HasForeignKey<Profile>(p => p.ApplicationUserId);
builder.Entity<IdentityRole>().HasData(
new IdentityRole() { Id = "1", Name = "Admin" },
new IdentityRole() { Id = "2", Name = "Client" }
new IdentityRole() { Id = "3", Name = "Authorized" }
);发布于 2022-06-13 19:44:44
您还没有定义变量userManager和roleManager。你指的是尚未被定义的事物。
请参见前面关于如何定义和初始化UserManager:How do i create an instance of UserManager实例的堆栈溢出问题。
https://stackoverflow.com/questions/72607935
复制相似问题