Session.Abandon(); Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
此代码示例从服务器中清除会话状态,并将会话状态 Cookie 设置为空值。空值可以有效地从浏览器中清除 Cookie。

当用户没有从应用程序注销并且发生会话状态超时时,应用程序可能仍将使用同一个会话状态 Cookie(如果没有关闭浏览器)。 此行为将导致用户转到登录页,并且提供用户的会话状态 Cookie。 为了保证在打开登录页 (login.aspx) 时使用新的 ID,应将空 Cookie 发送回客户端。为此,将 Cookie 添加到响应集合中。然后,将响应集合发送回客户端。发送空 Cookie 的最简单方法是通过使用“Response.Redirect”方法。由于 Cookie 集合对于 ASP.NET_SessionId 始终具有一个值,因此您不能仅仅测试此 Cookie 是否存在,这样将会创建一个“Response.Redirect”循环。可以针对重定向到登录页设置查询字符串。

或者,可以使用不同的 Cookie 来通知您是否已经重定向到登录页,如下面的代码示例所示。为了帮助提高安全性,确保没有任何用户尝试通过使用 ASP.NET Cookie 和另一个 Cookie 来打开登录页,下面的代码示例使用“FormsAuthentication”类来对 Cookie 数据进行加密和解密。然后,代码示例设置 5 秒钟的超时时间。
private void Page_Load(object sender, System.EventArgs e)
{
if( !IsPostBack &&
( Request.Cookies["__LOGINCOOKIE__"] == null ||
Request.Cookies["__LOGINCOOKIE__"].Value == "" ) )
{
//At this point, we do not know if the session ID that we have is a new
//session ID or if the session ID was passed by the client.
//Update the session ID.
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
//To make sure that the client clears the session ID cookie, respond to the client to tell
//it that we have responded. To do this, set another cookie.
AddRedirCookie();
Response.Redirect( Request.Path );
}
//Make sure that someone is not trying to spoof.
try
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt( Request.Cookies["__LOGINCOOKIE__"].Value );
if( ticket == null || ticket.Expired == true )
throw new Exception();
RemoveRedirCookie();
}
catch
{
//If someone is trying to spoof, do it again.
AddRedirCookie();
Response.Redirect( Request.Path );
}
Response.Write("Session.SessionID="+Session.SessionID+"<br/>");
Response.Write("Cookie ASP.NET_SessionId="+Request.Cookies["ASP.NET_SessionId"].Value+"<br/>");
}
private void RemoveRedirCookie()
{
Response.Cookies.Add(new HttpCookie("__LOGINCOOKIE__", ""));
}
private void AddRedirCookie()
{
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,"Test",DateTime.Now,DateTime.Now.AddSeconds(5), false,"");
string encryptedText = FormsAuthentication.Encrypt( ticket );
Response.Cookies.Add( new HttpCookie( "__LOGINCOOKIE__", encryptedText ) );
}
注意这句话:Session.Abandon(); Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
有人会问Session.Abandon(); 和Session.clear(); 有什么不一样,在这一并说明下吧



主要的不同之处在于当使用Session.Abandon时,会调用Session_End方法(InProc模式下)。
当下一个请求到来时将激发Session_Start方法。
而Session.Clear只是清除Session中的所有数据并不会中止该Session,因此也不会调用那些方法。
Session.Abandon()其实就等于将此次连接断开,而clear() 是没有断开