Today was another grind, which I finished at exactly noon, and I had already started working on it yesterday. What was it about? Nothing bigger than saving persistent (permanent) cookies. Because it is truly insane, I decided to put it on my blog so that others don’t have to go through these horrors too 😀 :
The args array is any number of values whose count is even, for example:
string[] args = new string[] { "login", txtLogin.Text };And now how it does not work.. for example like this:
for (int i = 0; i < args.Length; i++)
{
string name = args[i];
HttpCookie cookie = new HttpCookie(name, args[++i]);
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Set(cookie);
}It does not work like this either:
for (int i = 0; i < args.Length; i++)
{
string name = args[i];
page.Response.Cookies[name].Name = args[i];
page.Response.Cookies[name].Value = args[++i];
page.Response.Cookies[name].Expires = DateTime.Now.AddYears(1);
}Don’t even think about trying it with multi-value cookies:
//-I get a new cookie or take the old one, if it exists
HttpCookie cookie = GetExistsOrNew(page);
//-I tried to get the old cookie in a new way
for (int i = 0; i<args.Length; i++)
{
cookie.Values[args[i]] = args[++i];
}
//-Setting Expire as a value is pointless, even though I saw it described online as necessary for persistent cookies
cookie.Values["Expire"] = "5 Days";
cookie.Expires.AddDays(5);
cookie.Domain = M.wa;
//-Setting the Cookie property is pointless too; you do have to set it, but not in a multi-value cookie, only in a simple one
cookie.Value = "";
page.Response.Cookies.Add(cookie);All that is left is to write how it actually works – only like this:
for (int i = 0; i < args.Length; i++)
{
string name = args[i];
Response.Cookies[name].Name = args[i];
Response.Cookies[name].Value = args[++i];
Response.Cookies[name].Expires = DateTime.Now.AddYears(1);
}And finally, the only way to invalidate a cookie:
Response.Cookies["login"].Expires = DateTime.Now.AddYears(-1);So forget about deleting it this way:
Response.Cookies.Remove(M.ja);One more thing: adding the cookie must be done in the page code or in a page it derives from. I have not tried adding cookies via HttpContext.Current.