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

如何在ASP.NET Razor Pages中展示用户的已分配角色?

解决方案

1. 创建用户角色关联视图模型

先定义一个视图模型,用来封装用户信息和对应的角色集合,方便页面展示:

namespace LearLogin4.ViewModels
{
    public class UserWithRolesViewModel
    {
        public LearLogin4User User { get; set; } = default!;
        public IList<string> Roles { get; set; } = default!;
    }
}

2. 修改PageModel逻辑

更新IndexModel,替换原有的Users属性为视图模型集合,在OnGetAsync中遍历每个用户,获取其关联的角色:

namespace LearLogin4.Pages.RolesManager
{
    using LearLogin4.ViewModels;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    public class IndexModel : PageModel
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<LearLogin4User> _userManager;

        public IndexModel(RoleManager<IdentityRole> roleManager, UserManager<LearLogin4User> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }

        public IList<IdentityRole> Roles { get; set; } = default!;
        public IList<UserWithRolesViewModel> UsersWithRoles { get; set; } = default!;

        public async Task OnGetAsync()
        {
            var users = await _userManager.Users.ToListAsync();
            UsersWithRoles = new List<UserWithRolesViewModel>();

            foreach (var user in users)
            {
                var roles = await _userManager.GetRolesAsync(user);
                UsersWithRoles.Add(new UserWithRolesViewModel
                {
                    User = user,
                    Roles = roles
                });
            }

            Roles = await _roleManager.Roles.ToListAsync();
        }
    }
}

3. Razor页面展示示例

在RolesManager/Index.cshtml中,遍历UsersWithRoles集合,展示用户及其角色:

@page
@model LearLogin4.Pages.RolesManager.IndexModel

<h1>用户角色分配</h1>

<table class="table">
    <thead>
        <tr>
            <th>用户名</th>
            <th>邮箱</th>
            <th>所属角色</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.UsersWithRoles)
        {
            <tr>
                <td>@item.User.UserName</td>
                <td>@item.User.Email</td>
                <td>@string.Join(", ", item.Roles)</td>
            </tr>
        }
    </tbody>
</table>

关键说明

  • 使用UserManager<TUser>.GetRolesAsync(TUser user)方法可获取指定用户的所有角色名称,这是ASP.NET Identity提供的标准方法
  • 通过视图模型整合用户和角色数据,避免在页面中编写过多逻辑,符合关注点分离原则
  • 若用户数量较多需要优化性能,可直接查询Identity的关联表(如AspNetUserRoles),但上述标准方法兼容性更强、更易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:05:20