【发布时间】:2010-11-25 20:24:02
【问题描述】:
在我的 Web 应用程序中,我执行以下操作来读取会话变量:
if (HttpContext.Current.Session != null && HttpContext.Current.Session["MyVariable"] != null)
{
string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}
我明白为什么检查 HttpContext.Current.Session["MyVariable"] 为 null 的原因很重要(变量可能尚未存储在 Session 中,或者由于各种原因 Session 已被重置),但为什么我要需要检查HttpContext.Current.Session 是否为空?
我的理解是会话是由 ASP.NET 自动创建的,因此 HttpContext.Current.Session 永远不应为空。这个假设正确吗?如果它可以为空,是否意味着我也应该在存储内容之前对其进行检查:
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["MyVariable"]="Test";
}
else
{
// What should be done in this case (if session is null)?
// Is it possible to force the session to be created if it doesn't exist?
}
【问题讨论】:
-
ASP.NET WebApi 会有不同的行为,你可以在Accessing Session Using ASP.NET Web API查看它