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

ASP.NET Identity MVC中如何在视图显示角色名而非角色ID

解决方案

1. 修正视图代码(解决直接报错)

报错核心原因:控制器传递给视图的是List<UserDto>集合,视图却错误访问Model.Users(该集合本身无此属性);同时视图对UserDto属性的引用也不匹配类定义。调整后的视图代码如下:

@model List<MyAppName.Models.UserDto>

<table>
    <thead>
        <tr>
            <th>邮箱</th>
            <th>公司名称</th>
            <th>角色</th>
            <th>登录信息</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var userDto in Model)
        {
            var appUser = userDto.User;
            var roles = userDto.Roles;
            <tr>
                <td class="email">
                    @appUser.Email
                </td>
                <td>
                    @appUser.CompanyName
                </td>
                <td>
                    @string.Join(",", roles)
                </td>
                <td>
                    @(appUser.Logins != null ? string.Join(", ", appUser.Logins.Select(l => l.LoginProvider)) : "无")
                </td>
                <td>
                    @Html.ActionLink("编辑", "Edit", new { id = appUser.Id }, new { @class = "edit-link" }) |
                    @Html.ActionLink("删除", "Delete", new { id = appUser.Id }, new { @class = "delete-link" })
                </td>
            </tr>
        }
    </tbody>
</table>

关键修正点:

  • 视图顶部明确指定模型类型为List<UserDto>
  • 直接遍历Model(它就是用户集合),而非Model.Users
  • 将user.ApplicationUser改为userDto.User(匹配UserDto类的属性名)
  • 优化@appUser.Logins显示逻辑,避免直接输出对象
  • 操作链接ID改为appUser.Id(ID存储在User对象中)

2. 优化控制器查询(提升性能与可读性)

原查询逻辑可行,但可简化写法并遵循依赖注入原则:

private readonly ApplicationDbContext _context;

// 通过构造函数注入DbContext,避免手动实例化
public UsersController(ApplicationDbContext context)
{
    _context = context;
}

// GET: Users
public ActionResult Index()
{
    var usersWithRoles = _context.Users
        .Select(u => new UserDto
        {
            User = u,
            Roles = _context.Set<IdentityUserRole>()
                .Where(ur => ur.UserId == u.Id)
                .Join(_context.Roles, ur => ur.RoleId, r => r.Id, (ur, r) => r.Name)
                .ToList()
        })
        .ToList();

    return View(usersWithRoles);
}

优化点:

  • 采用构造函数注入ApplicationDbContext,符合.NET设计规范
  • 简化LINQ查询结构,逻辑更清晰
  • 确保仅执行一次数据库查询(通过ToList()触发)

3. 规范UserDto类定义

确保类引用正确的ApplicationUser类型:

using Microsoft.AspNet.Identity.EntityFramework;

public class UserDto
{
    public ApplicationUser User { get; set; }
    public List<string> Roles { get; set; }
}

可选:使用UserManager获取角色(更符合Identity设计)

如果项目基于ASP.NET Identity 2.x及以上版本,推荐通过UserManager操作角色,无需直接访问中间表:

private readonly UserManager<ApplicationUser> _userManager;

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

public async Task<ActionResult> Index()
{
    var users = _context.Users.ToList();
    var userDtos = new List<UserDto>();

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

    return View(userDtos);
}

内容的提问来源于stack exchange,提问作者Kip M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:40:32