I create an HttpCookie by setting only the name and value, not the expires property, and then adding it to the response. Simple enough. A cookie is created (but not saved), as expected. The problem is that for some reason the session is changing (for example, the site was rebuilt or I rebuilt the application during debugging), then the cookie stays around. I want the cookie to be valid only for the original session in which it was created.
According to MSDN, it says: "If you have not specified a cookie expiration, the cookie is not saved on the client computer and expires when the user session expires."
I think I don’t know what exactly means "session expires." I believe that the cookie is deleted after 20 minutes when the session expires. But should a cookie be deleted if the session in which it was created no longer exists for a number of reasons? The only time I saw that a cookie is being deleted is when the user closes all browser windows and opens a new one.
If all this is true, I may need to save the original session identifier ("ASP.NET_SessionId") in a cookie, and then check it for the current session identifier, if they are different, then delete the cookie or create a new one.
Here is the code (the only difference between my cookie and what is in the MSDN examples, I store several values in a cookie):
private void SaveValuesToCookie(string[] names, string[] values)
{
HttpCookie cookie = new HttpCookie("MyCookie");
for (int i = 0; i < names.Length; i++)
{
string name = names[i];
cookie.Values[name] = values[i];
}
Response.Cookies.Add(cookie);
}
private string GetValueFromCookie(string name)
{
HttpCookie cookie = Request.Cookies["MyCookie"];
if (cookie == null)
return null;
return cookie.Values[name];
}