2015-05-07 38 views
2

我的會話沒有被破壞。這就是我在Login.aspx.cs設置它:如何從Session中刪除值?

Session["User"] = UserName.Text; // Set the session called User. 

在母版鏈接:

<a href="Login.aspx" id="loginButton"><img src="images/login.png"><span runat="server" id="authspan">Login</span></a> 

在這取決於用戶是否具有會話或沒有鏈接的文字發生變化:

if (Session["User"] != null) 
    { 
     authspan.InnerHtml = "Logout"; 
    } 
    else 
    { 
     authspan.InnerHtml = "Login"; 
    } 

此鏈接重定向到Login.aspx文件,其中PageLoad我告訴代碼關閉會話。理論上,這應該工作,對吧?

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["User"] != null) 
    { 
     Response.Redirect("Default.aspx"); // Redirect user. 
     Session["User"] = null; 
     Session.Remove("User"); 
    } 
    else 
    { 
     // run code that logs the user in, and sets up the session. 
    } 

} 

如何正確結束登錄用戶?

+2

你不是要破壞會話,只是從中刪除一個值,對嗎? – mason

+0

正確,道歉不正確的措辭。仍在學習。 – hf185

回答

5

您必須先清除會話然後重定向。

Session["User"] = null; 
    Session.Remove("User"); 
    Response.Redirect("Default.aspx"); // Redirect user. 

還要注意的是,它是安全去除客戶端太會話ID:

var sessionCookie = new HttpCookie("ASP.NET_SessionId"); 
    sessionCookie.Expires = DateTime.Now.AddDays(-1); 
    Response.Cookies.Add(sessionCookie); 
+0

謝謝,那有效:) – hf185

0

你應該使用:

Session.Clear(); 
Response.Redirect("Default.aspx"); 
0

呼叫Session.Abandon();(我必須至少寫30個字符)

1

以不同方式從會話中刪除值

//Set the session variable 
Session["User"]=Value; 
//Destroy the session variable 
Session.Remove("User"); 
Session["User"]=null; 

//放棄將徹底摧毀了會議,這意味着你需要開始一個新的會話之前,你可以存儲更多的價值就在該用戶 Session.Abandon會話(); //清除會話不會取消設置會話,它仍然存在與用戶相同的ID,但只需清除值。 Session.Clear();