How to kill current session in Asp.Net?<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to kill current session in Asp.Net?

Posted on: July 11, 2012

If you need to kill your current session, which is the case if a user logout, you need to kill cookies and sessions.

To kill cookies, you have to set the expiry to something already passed like the yesterday date. For the session, you can use the method "Abandon".

The Abandon method destroys all the objects stored in a Session object and releases their resources. The resources are not deleted right away, which mean that you still have access to the data of the session until the page is generated.

1HttpContext.Current.Session.Abandon();

Session are stored in a cookie with the name "ASP.NET_SessionId". You need to kill this cookie like you would do with any cookie.

1var sessionCookie = new HttpCookie("ASP.NET_SessionId", string.Empty); sessionCookie.Expires = DateTime.Now.AddDays(-1); sessionCookie.Domain = UrlInformation.GetHostDomain(HttpContext.Current.Request.Url.Host); HttpContext.Current.Response.Cookies.Add(sessionCookie);

With those two snippets of code, the session should be killed for good.