如何在aspx页面中检查新会话?

时间:2012-09-18 06:52:39

标签: c# asp.net

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

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

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

5 个答案:

答案 0 :(得分:0)

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

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

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

var sessionValue = SESSION["DETAILS"];
if(string.IsNullOrEmpty(sessionValue))
{
   // session is "new", i.e. the value was not set
}

答案 1 :(得分: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")检查会话是否等于相关字符串。

答案 2 :(得分:0)

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

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

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

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

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

用于将会话值与其他值进行比较(在本例中为=>“new”)

答案 3 :(得分: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]";
    }
}

Ref

答案 4 :(得分:0)

您可能会发现这个有用的

Session.IsNewSession

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

并且为了解释你得到了很多答案,@ kakarott是精确而小的