Tuesday, July 15, 2008

Understanding Session.Abandon

When the web application requires a log off based on session, clear the session state or call abandon(Session.Abandon) method.
Session.Abandon flushes the session state. The Abandon method sets flag which tells the session state needs to be abandoned.

The flag is evaluated at the end of the page request and action takes based on the status of the flag.
As soon as page processing is done, the session is removed.
When Session.Abandon is called, the session ID cookie is not removed for the browser.
Even after Session.Abandon call, any new request to the application uses the same Session ID with new session state instance.

If user opens another application within the same DNS domain, the user will not lose their session state after the Abandon method is called from the application.

To make session ID cookie null and to get rid of above problem, use the below code

Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

To assure that when user opens the log on page send null cookie to the client. The simple way to send a null cookie is using Response.Redirect.

Lets try one example :

create one aspx page and put below code in Page_Load

Response.Write(Session.SessionID + "
");
Session.Abandon();
Response.Write(Session.SessionID + "
");

you will get same SessionID before and after Session.Abandon

Lets create one more aspx with the below code

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && (Request.Cookies["TESTLOGIN"] == null || Request.Cookies["TESTLOGIN"].Value == ""))
{
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
AddCookie();
Response.Redirect(Request.Path);
}
Response.Write("Session.SessionID=" + Session.SessionID + "
");
Response.Write("Cookie ASP.NET_SessionId=" + Request.Cookies["ASP.NET_SessionId"].Value + "
");
}


private void AddCookie()
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "TestCookie", DateTime.Now, DateTime.Now.AddSeconds(5), false,"");
string encryptedText = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie("TESTLOGIN", encryptedText));
}

I have used a different cookie to find out whether I am redirected to the logon page.

Add watch and check Session.SessionId value. You will notice that session ID will change.

Happy Coding :)

2 comments:

forex trading said...

Hi thanx its very useful. before that I have tried many things but couldn't have result which i want . Once again thanx a lot for such a useful post.

Anonymous said...

Great! Really working. Many thanks.

Site Meter