Home » ASP » How to kill current session in Asp.Net?

How to kill current session in Asp.Net?

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.

     HttpContext.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.

                var 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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.