Weird Cookie Behaviour

G

Guest

I am trying to perform site login using values from a cookie, but for some
weird reason the cookie is being destroyed after the browser window is
closed. I checked the browser settings for the cookies, and there is nothing
there that terminates cookies uopn browser close. The following is a sample
of the code I am runinng:

To write the cookie:
This code runs if the user is not logged on the site and the cookie does not
exist.

writeCookie(string user, string password)
{
try
{
HttpCookie loginCookie = new HttpCookie(cookieName);
Response.Cookies.Clear();
Response.Cookies.Add(loginCookie);
loginCookie.Values.Add(cookieName, user + " " + password);
}
catch
{
}
}

The code to retrieve the cookie does so by getting the value of the cookie
and login on the user. I get the value of the cookie this way:

cookieValue = Request.Cookies[cookieName].Value;

The whole t hing is that this code is on the onLoad event of the form. It's
supposed to get the values of the cookie, but I get a null reference
exception because the cookie does not exist even though I wrote it with the
code above.
Can anyone help?

HS
 
S

Steve Lutz

I believe you need to set the expiration date of the cookie:

loginCookie.Expires = DateTime.Now.AddDays(x);
(or something like that)

Without the expiration date, I believe the cookie becomes a "session" cookie
and is destroyed when the browser exits.

Also, if you write the cookie, then redirect the user on the same page, some
browsers will not accept the cookie. (Older netscapes I believe)

HTH

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top