在我的Web应用程序中,我执行类似这样的操作来读取会话变量:
if (HttpContext.Current.Session != null && HttpContext.Current.Session["MyVariable"] != null)
{
string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}
Run Code Online (Sandbox Code Playgroud)
我理解为什么重要的是要检查为什么HttpContext.Current.Session ["MyVariable"]为空(该变量可能尚未存储在会话中,或者会因各种原因重置了会话),但为什么我需要检查如果HttpContext.Current.Session是null?
我的理解是,会话是由ASP.NET自动创建的,因此HttpContext.Current.Session永远不应为null.这个假设是否正确?如果它可以为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?
}
Run Code Online (Sandbox Code Playgroud)