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

如何从Login Controller获取用户ID并传递至其他控制器与视图?

在ASP.NET MVC中传递用户ID到其他控制器和视图的几种方法

结合你提供的Login Controller代码,以下是几种实用的实现方式:

方法1:利用FormsAuthenticationTicket存储用户ID(推荐,全局持久可用)

FormsAuthentication的Cookie支持嵌入自定义数据,能让你在任意控制器或视图中通过User.Identity获取用户ID:

  1. 修改Login控制器的登录成功逻辑:
if (SecurityAlgorithms.CheckMD5Hash(user.UserPassword, user1.UserPassword))
{
    // 创建包含用户ID的认证票据
    var authTicket = new FormsAuthenticationTicket(
        1,
        user1.UserName,
        DateTime.Now,
        DateTime.Now.AddMinutes(30), // 设置Cookie过期时间
        false,
        user1.UserId.ToString() // 这里存入用户ID
    );

    // 加密票据并写入Cookie
    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    Response.Cookies.Add(authCookie);

    Session["user1"] = user1.UserName;
    return RedirectToAction("Index", "Home");
}
  1. 新增一个IIdentity扩展方法,方便全局获取用户ID:
public static class IdentityExtensions
{
    public static int GetUserId(this IIdentity identity)
    {
        var formsIdentity = identity as FormsIdentity;
        if (formsIdentity != null && !string.IsNullOrEmpty(formsIdentity.Ticket.UserData))
        {
            if (int.TryParse(formsIdentity.Ticket.UserData, out int userId))
            {
                return userId;
            }
        }
        return -1; // 未找到时返回默认值
    }
}
  1. 在其他控制器中获取:
public ActionResult Index()
{
    int userId = User.Identity.GetUserId();
    // 用userId执行业务逻辑
    return View();
}
  1. 在视图中直接调用:
<p>当前用户ID:@User.Identity.GetUserId()</p>

方法2:使用Session存储用户ID(简单直接)

登录时把用户ID存入Session,后续在任意控制器/视图中直接读取:

  1. 修改Login控制器的登录成功代码:
if (SecurityAlgorithms.CheckMD5Hash(user.UserPassword, user1.UserPassword))
{
    FormsAuthentication.SetAuthCookie(user1.UserName, false);
    Session["user1"] = user1.UserName;
    Session["userId"] = user1.UserId; // 新增存储用户ID

    return RedirectToAction("Index", "Home");
}
  1. 在其他控制器中获取:
public ActionResult Index()
{
    int userId = -1;
    if (Session["userId"] != null)
    {
        userId = Convert.ToInt32(Session["userId"]);
    }
    // 业务逻辑处理
    return View();
}
  1. 在视图中获取:
@{
    int userId = Session["userId"] != null ? Convert.ToInt32(Session["userId"]) : -1;
}
<p>当前用户ID:@userId</p>

方法3:通过路由参数/ViewBag传递(单次请求场景)

如果仅需在登录跳转时一次性传递用户ID给目标控制器,可使用路由参数:

  1. 修改Login控制器的跳转代码:
return RedirectToAction("Index", "Home", new { userId = user1.UserId });
  1. 在Home控制器的Index方法接收参数:
public ActionResult Index(int userId)
{
    ViewBag.UserId = userId; // 传递给视图
    return View();
}
  1. 在视图中显示:
<p>当前用户ID:@ViewBag.UserId</p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:27:24