ASP.NET - Expire Cookie When User Closes the Browser

I had a need for Site A to communicate a value to Site B on the same domain. I wanted to do this through a cookie and if the user closed Site A the cookie would expire.  This can be done by not setting a expiration date on the cookie. 
//------------------------------------------------
// Site A - Create a cookie with no expiration  
//------------------------------------------------
private void SetCoookieValue()
{
  HttpContext CTX = HttpContext.Current;
  var CookieValue = 'TEST';
  
  var CookieName = "MY_COOKIE";
  HttpCookie MyCookie = new HttpCookie(CookieName);
  if (CTX.Request.Cookies[CookieName] != null) MyCookie = CTX.Request.Cookies[CookieName];
    
  MyCookie.Value = CTX.Server.UrlEncode(CookieValue);
    
  //No Expiration - it will expire when the user closes the browser
  //MyCookie.Expires = DateTime.Now.AddHours(8);
  CTX.Response.Cookies.Add(MyCookie);
}
    
//------------------------------------------------    
// Site B - Attempt to read the cookie in, 
// it should be gone after closing Site A
//------------------------------------------------  
private string GetCookieValue(string cookieName, string itemName)
{
    var CookieName = "MY_COOKIE";
    var CookieValue = string.empty;

    HttpCookie myCookie = Request.Cookies[CookieName];
    if (myCookie == null) return "No cookie found";

    //If you added a key vs. the value in the cookie
    //CookieValue = myCookie[itemName].ToString();

    //Get the value of the cookie 
    CookieValue = Page.Server.UrlDecode(myCookie.Value.ToString());
}

Comments are closed