How to delete all the cookies of the project after session timeout? and it will also reflect in browser window.
Loading
How to delete all the cookies of the project after session timeout? and it will also reflect in browser window.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Ali BenchaabanRank #925 · 2.2K reputationPosted Apr 3, 2023, 5:18 AM EDT
Hello Brahma Prakash Shukla,
Try this method
private void ExpireAllCookies() { if (HttpContext.Current != null) { int cookieCount = HttpContext.Current.Request.Cookies.Count; for (var i = 0; i < cookieCount; i++) { var cookie = HttpContext.Current.Request.Cookies[i]; if (cookie != null) { var expiredCookie = new HttpCookie(cookie.Name) { Expires = DateTime.Now.AddDays(-1), Domain = cookie.Domain }; HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it } } // clear cookies server side HttpContext.Current.Request.Cookies.Clear(); } }BENCHAABAN Ali
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Apr 3, 2023, 5:32 AM EDT
I want to apply this on global.asax file on session end method, it will work or not ?
Ali BenchaabanRank #925 · 2.2K reputationPosted Apr 3, 2023, 5:54 AM EDT
yes, it should work with Session_End method.
keep us informed if it works or not, thank you
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Apr 3, 2023, 6:00 AM EDT
It is not working as session ends is not taking cookies using HttpContext.Current.Request.Cookies.To avoid it we need to set cookies on the start of session .
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
// Store a reference to the HttpContext object in the session
Session["HttpContext"] = HttpContext.Current;
}
But this way it id not taking cookies which were applied on page load of any other page.
Amit MohantyRank #112 · 20K reputationPosted Apr 3, 2023, 6:14 AM EDT
Try this
void Session_End(object sender, EventArgs e) { foreach (string cookieName in Request.Cookies.AllKeys) { HttpCookie cookie = Request.Cookies[cookieName]; cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookie); } }Ali BenchaabanRank #925 · 2.2K reputationPosted Apr 3, 2023, 6:24 AM EDT
Try this
void Session_End(object sender, EventArgs e) { int cookieCount = HttpContext.Current.Request.Cookies.Count; for (int i = 0; i < cookieCount; i++) { HttpCookie expiredCookie = new HttpCookie(Request.Cookies[i].Name); expiredCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(expiredCookie); } }Jignesh KumarRank #91 · 22.9K reputationPosted Apr 3, 2023, 10:15 AM EDT
Hello Brahma prakash,
You can do this in the session_end event by adding the code below.
void Session_End(object sender, EventArgs e) { Response.Cookies.Clear(); }