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

如何在ASP.NET Core 2控制器中获取所有用户列表?

嘿,我之前在ASP.NET Core 2项目里刚好折腾过获取所有用户的需求,和老ASP.NET MVC的路子确实不一样,给你详细捋一遍操作步骤:

在ASP.NET Core 2中获取所有用户的步骤

1. 核心工具:UserManager

ASP.NET Core 2里的用户管理是基于ASP.NET Core Identity框架的,要拿全量用户,核心就是用UserManager<TUser>这个类——它封装了所有用户相关的操作,包括查询全部用户的能力。

2. 在控制器中注入并使用UserManager

首先得把UserManager注入到控制器里,然后就能在Action里调用它的方法来获取用户列表了。

示例代码(用默认IdentityUser):

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;

public class UserController : Controller
{
    // 存一下注入的UserManager实例
    private readonly UserManager<IdentityUser> _userManager;

    // 构造函数注入UserManager
    public UserController(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    // 获取所有用户的Action
    public async Task<IActionResult> AllUsers()
    {
        // 从UserManager里拿到用户查询集合,转成列表
        var allUsers = await _userManager.Users.ToListAsync();
        
        // MVC控制器就返回视图+用户列表
        return View(allUsers);
        
        // 如果是API控制器,直接返回JSON格式
        // return Ok(allUsers);
    }
}

如果用自定义用户类(比如ApplicationUser):

要是你自己继承了IdentityUser做了自定义用户类(比如ApplicationUser),只需要把代码里的IdentityUser替换成你的自定义类就行:

private readonly UserManager<ApplicationUser> _userManager;

public UserController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

3. 几个关键注意点

  • 先确认Identity配置好了:在Startup.cs的ConfigureServices里,你得已经注册了Identity服务,大概是这样的:
    services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<YourDbContext>();
    
    这里的YourDbContext是你项目里继承了IdentityDbContext的数据库上下文类。
  • 尽量用异步操作:_userManager.Users是个IQueryable集合,推荐用ToListAsync()异步方法拿数据,避免同步调用搞出性能问题或者死锁。
  • 按需筛选用户:要是不需要全量用户,加个Linq条件就行,比如只拿邮箱已验证的用户:
    var verifiedUsers = await _userManager.Users
                                          .Where(u => u.EmailConfirmed)
                                          .ToListAsync();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:50:33