You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC 管理员通过UserId封禁用户的实现方案

问题背景

我刚接触MVC和Identity Framework,正在做管理员封禁用户的功能,看了大量视频和教程反而越看越混乱。现有公开教程全是基于Identity Framework的封装实现,我想找逻辑更简单易懂的方案,避开复杂的框架封装调用;就算跟着教程一步步操作,调用userManager方法时也一直报错,我既不清楚userManager的定义位置,也不知道该怎么完成它的实例化和初始化。我的项目配置了两个独立数据库,分别存储项目业务数据和Identity身份认证数据。

已编写代码

管理员视图代码

<form>
<div class="mb-5 w-50">
    <label asp-for="UserId" class="form-label">User Id: </label>
    <input asp-for="UserId" class="form-control" />
</div>
<div class="mb-5">
    <a class="btn btn-primary" asp-action="BanUser">Ban this user</a>
</div>
</form>

Admin控制器代码

public class AdminController : Controller
{
    private readonly ILogger<AdminController> _logger;

    public AdminController(ILogger<AdminController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

    public IActionResult BanUser()
    {
        return View();
    }
}

ApplicationUser类代码

public class ApplicationUser : IdentityUser
{
    public virtual Profile? Profile { get; set; }
}

Profile类代码

public class Profile
{
    public int ProfileId { get; set; }
    public string? Name{ get; set; }
    public string? ApplicationUserId { get; set; }
    public virtual ApplicationUser? ApplicationUser { get; set; }
}

静态仓储类代码

public static class Repository
{
    public static List<Profile> Profile
    {
        get
        {
            ApplicationDbContext dataBase = new ApplicationDbContext();
            List<Profile> profiles = dataBase.Profiles.ToList();
            return profiles;
        }
    }

    public static void NewProfile(Profile newProfile)
    {
        ApplicationDbContext dataBase = new ApplicationDbContext();
        dataBase.Profiles.Add(newProfile);
        dataBase.SaveChanges();
    }
}

Profile视图模型代码

public class ProfileViewModel
{
    public Profile newProfile { 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 = "User" },
            new IdentityRole() { Id = "3", Name = "unbanned" }
        );
    }
}

当前卡点

我查阅的所有相关教程都依赖userManager组件完成角色操作,但我没法正常访问、调用这个组件,还有部分教程基于旧版本ASP.NET Core编写,进一步提高了理解成本。目前开发完全卡住,查阅的资料越多越理不清实现逻辑。

注:贴出的原始代码存在几处语法问题:包括HasData方法中第二条角色种子数据末尾缺失逗号、控制器和DbContext类末尾缺失闭合大括号,调试前需要先修复这些基础语法错误。


内容的提问来源于stack exchange,提问作者qwerty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 21:15:37