0

如何在 aspx 页面中检查新会话?以下三行检查会话有什么区别

1. if (Session["DETAILS"] == null) 
2. if (Session["DETAILS"] == "")
3. if (Session["DETAILS"].ToString() == "new")

请帮助我如何在 aspx 页面的页面加载事件中检查会话。所以我需要如果会话是新的,我需要输入新的值。如果会话是编辑,我需要编辑已经存在的值。

4

5 回答 5

0

前两个if语句检查 key 标识的会话值DETAILS是否存储在当前会话中。

NullReferenceException当具有给定键的对象未存储在会话中并且调用导致null引用时,第三个可能会抛出 a 。这是不安全的。

如果我做对了,当密钥不在会话中时,会话是“新的”。它还取决于值的类型,因此string代码可能看起来像

var sessionValue = SESSION["DETAILS"];
if(string.IsNullOrEmpty(sessionValue))
{
   // session is "new", i.e. the value was not set
}
于 2012-09-18T07:01:25.170 回答
0

如果通过“新会话”,您的意思是检查会话是否为空,然后使用

if(string.isNullOrEmpty(Session["Obj"].toString())) //This will return true or false
{
   //Do this if true
}
else
{
   //Do this if false
   //Below will force the session to be cleared
   Session.Abandon();
   Session.Clear();
   Response.Redirect(Request.RawUrl); //Which will reload the current page
}  

if (Session["DETAILS"]== null)检查会话是否为空,
if (Session["DETAILS"]== "")检查会话字符串是否为空,

注意上面两个可以换成 string.isNullOrEmpty(Session["Obj"].toString());

if (Session["DETAILS"].tostring()== "new")检查会话是否等于相关字符串。

于 2012-09-18T07:01:46.527 回答
0
if (Session["DETAILS"]== null) 

用于检查会话是否存在。(如果会话存在与否)

if (Session["DETAILS"]== "")

用于检查会话是否为空(不包含任何值。)

if (Session["DETAILS"].tostring()== "new")

用于将 Session 值与其他值进行比较(在这种情况下 => “new”)

于 2012-09-18T07:04:08.040 回答
0

查看 Global.asx 中的事件,尤其是 Session_Start 和 Session_End 事件:

protected void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
    if (HttpContext.Current.Session["DETAILS"] != null)
    {
        HttpContext.Current.Session["DETAILS"] = "[type here your data]";
    }
}

参考

于 2012-09-18T07:04:55.540 回答
0

您可能会发现这很有帮助

Session.IsNewSession

更多信息:http: //msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.isnewsession.aspx

对于解释,您得到了很多答案,而@kakarott 的答案又精确又小

于 2012-09-18T07:09:48.503 回答