You need to enable JavaScript to run this app. 求助:ASP.NET MVC基于用户角色实现登录后定向跳转
优惠活动
大模型
产品
解决方案
定价
更多

求助:ASP.NET MVC基于用户角色实现登录后定向跳转

ASP.NET MVC 登录后按角色重定向问题

在开发ASP.NET MVC身份认证功能时,已完成登录Action编写,但无法根据登录用户所属角色重定向到对应页面。当前已定义三类角色:Admin、Auditor、Employee,现有代码结构如下:

现有代码结构

1. User 实体类

public class User
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

2. RoleMaster 角色主表实体类

public class RoleMaster
{
    [Key]
    public int RoleID { get; set; }
    public string RollName { get; set; }
}

3. 自定义角色提供类 UserRoleProvider(继承自 RoleProvider)

public class UserRoleProvider : RoleProvider
{
    public override string ApplicationName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override void CreateRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        throw new NotImplementedException();
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        throw new NotImplementedException();
    }

    public override string[] GetAllRoles()
    {
        throw new NotImplementedException();
    }

    public override string[] GetRolesForUser(string username)
    {
        using (Db context = new Db())
        {
            var userRoles = (from user in context.Users
                             join roleMapping in context.UserRolesMappings
                             on user.Id equals roleMapping.Id
                             join role in context.RoleMasters
                             on roleMapping.RoleID equals role.RoleID
                             where user.Username == username
                             select role.RollName).ToArray();
            return userRoles;
        }
    }

    public override string[] GetUsersInRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        throw new NotImplementedException();
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override bool RoleExists(string roleName)
    {
        throw new NotImplementedException();
    }
}

4. 用户-角色关联映射类 UserRolesMapping

public class UserRolesMapping
{
    [Key]
    public int URMID { get; set; }
    public int Id { get; set; }
    public int RoleID { get; set; }

    [ForeignKey("Id")]
    public virtual User Users { get; set; }
    public IEnumerable<SelectListItem> User { get; set; }

    [ForeignKey("RoleID")]
    public virtual RoleMaster RoleMasters { get; set; }
    public IEnumerable<SelectListItem> RoleMaster { get; set; }
}

5. 登录表单视图代码

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
        <div class="card card-signin my-5">
            <div class="card-body">
                <h5 class="card-title text-center">TickeTool</h5>
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <form class="form-signin">
                    <div class="form-group">
                        @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control col-md-12",@placeholder="Username here.." } })
                        @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                    </div>

                    <div class="form-group">
                        @Html.PasswordFor(model => model.Password,new { @class = "form-control col-md-12",@placeholder="Password here.."  })
                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                    </div>

                    <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button>
                    <hr class="my-4">
                </form>
            </div>
        </div>
    </div>
}

6. 登录请求处理 Action 代码

[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult Login(User model)
{
    if (ModelState.IsValid)
    {
        using (Db db = new Db())
        {
            bool isValidUser = db.Users.Any(x => x.Username == model.Username && x.Password == model.Password);

            if (isValidUser)
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);
                return RedirectToAction("MyTickets", "Ticket");
            }
            else
            {
                bool isUserValid = db.Users.Any(x => x.Username != model.Username && x.Password != model.Password);
                if (isUserValid)
                {
                    ModelState.AddModelError("", "Username / Password is Invalid");
                    return View(model);
                }
            }
        }
    }
    return View();
}

角色匹配重定向实现方案

前置配置

首先在Web.config的<system.web>节点下注册自定义角色提供类,否则无法调用已实现的角色查询逻辑:

<roleManager enabled="true" defaultProvider="UserRoleProvider">
  <providers>
    <add name="UserRoleProvider" type="你的项目命名空间.UserRoleProvider" />
  </providers>
</roleManager>

注意将你的项目命名空间替换为实际的项目命名空间。

修改登录Action逻辑

当前登录代码验证用户通过后固定重定向,需要新增角色查询、分支匹配逻辑:

  1. 用户身份校验通过后,获取当前用户的角色列表
  2. 按预设的角色优先级匹配对应的跳转地址
  3. 兜底处理无匹配角色的场景
    修改后的参考代码:
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult Login(User model)
{
    if (ModelState.IsValid)
    {
        using (Db db = new Db())
        {
            bool isValidUser = db.Users.Any(x => x.Username == model.Username && x.Password == model.Password);

            if (isValidUser)
            {
                FormsAuthentication.SetAuthCookie(model.Username, createPersistentCookie: false);

                // 获取当前用户的角色列表
                string[] userRoles = Roles.GetRolesForUser(model.Username);
                
                // 按角色优先级匹配重定向地址
                if (userRoles.Contains("Admin"))
                {
                    return RedirectToAction("Dashboard", "Admin");
                }
                else if (userRoles.Contains("Auditor"))
                {
                    return RedirectToAction("AuditLog", "Audit");
                }
                else if (userRoles.Contains("Employee"))
                {
                    return RedirectToAction("MyTickets", "Ticket");
                }

                // 无匹配角色时跳转默认首页
                return RedirectToAction("Index", "Home");
            }
            else
            {
                // 简化原冗余的错误判断逻辑
                ModelState.AddModelError("", "Username / Password is Invalid");
                return View(model);
            }
        }
    }
    return View();
}

可选优化

  • 如果不想依赖全局RoleProvider配置,可以直接在登录Action中用EF查询用户角色,逻辑更直观:
    var userRoleNames = (from u in db.Users
                         join mapping in db.UserRolesMappings on u.Id equals mapping.Id
                         join role in db.RoleMasters on mapping.RoleID equals role.RoleID
                         where u.Username == model.Username
                         select role.RollName).ToList();
    
  • RoleMaster中的RollName字段疑似拼写错误,建议修正为RoleName减少后续维护混淆
  • UserRolesMapping实体类中多余的SelectListItem属性建议移除,实体类仅保留数据库映射字段,视图绑定逻辑放在对应视图模型中实现
  • 当前密码为明文存储,建议替换为哈希加密存储,降低安全风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.25 03:45:07