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

如何在ASP.NET MVC不同控制器之间传递Session变量?

我已为用户登录功能创建了Session,代码如下:

[HttpPost]
public ActionResult Index(UserLogin lc)
{
    string mainconn = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    SqlConnection sqlconn = new SqlConnection(mainconn);
    SqlCommand sqlcomm = new SqlCommand("UserLogin");
    sqlconn.Open();
    sqlcomm.Connection = sqlconn;
    sqlcomm.CommandType = CommandType.StoredProcedure;
    sqlcomm.Parameters.AddWithValue("@Email", lc.Email);
    sqlcomm.Parameters.AddWithValue("@Password", lc.Password);
    SqlDataReader sdr = sqlcomm.ExecuteReader();
    
    if(sdr.Read())
    {
        FormsAuthentication.SetAuthCookie(lc.Email, true);
        Session["Email"] = lc.Email.ToString();
        return RedirectToAction("Welcome");
    }
}

现在我需要在另一个控制器中使用此处存储的Session变量,请问该如何操作?

在其他控制器中访问Session变量的方法

直接读取Session属性

所有继承自Controller的控制器都可以直接通过Session属性访问已存储的变量,示例代码如下:

public class AnotherController : Controller
{
    public ActionResult YourAction()
    {
        // 从Session中取出Email,用as string避免强制转换异常
        string userEmail = Session["Email"] as string;

        // 必须做空值校验,防止Session过期或未登录的情况
        if (!string.IsNullOrEmpty(userEmail))
        {
            // 这里可以使用userEmail执行业务逻辑,比如传递到View
            ViewBag.CurrentUserEmail = userEmail;
        }
        else
        {
            // Session不存在时,跳转到登录页
            return RedirectToAction("Index", "Login");
        }

        return View();
    }
}

更优方案:利用FormsAuthentication替代Session

你已经调用了FormsAuthentication.SetAuthCookie(lc.Email, true),这意味着用户邮箱已经被存储在加密的身份认证票据中,完全可以直接通过User.Identity.Name获取,无需依赖Session:

public class AnotherController : Controller
{
    public ActionResult YourAction()
    {
        string userEmail = User.Identity.Name;

        if (!string.IsNullOrEmpty(userEmail))
        {
            ViewBag.CurrentUserEmail = userEmail;
        }
        else
        {
            return RedirectToAction("Index", "Login");
        }

        return View();
    }
}

关键注意点

  • ASP.NET MVC默认启用Session状态,若你手动关闭过,需要在Web.config中重新启用。
  • Session有超时限制(默认20分钟),超时后Session["Email"]会返回null,所以空值校验必不可少。
  • 使用User.Identity.Name的方式更安全可靠,因为身份认证票据是加密存储的,不会像Session那样容易因服务器配置或负载均衡问题失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:20:13