在我的web应用程序,我做这样的事情读会话变量:如果当前的ASP.NET会话为空,我应该怎么做?
if (HttpContext.Current.Session != null && HttpContext.Current.Session["MyVariable"] != null)
{
string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}
我明白为什么它来检查为什么HttpContext.Current.Session [“MyVariable的”]为空是很重要的(变量可能不已存储在Session中,或者会话因各种原因已被重置),但为什么我需要检查HttpContext.Current.Session
是否为空?
我的理解是会话是由ASP.NET自动创建的,因此HttpContext.Current.Session不应该为null。这个假设是否正确?如果它可以为空,这是否意味着我也应该在其存储的东西之前检查:
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将有diferent行为,您可以检查它的[访问会话使用的ASP.NET Web API(http://stackoverflow.com/questions/9594229/accessing-session-using -asp-net-web-api?answertab = votes#tab-top) – 2016-04-15 13:46:56