By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,395 Members | 2,513 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,395 IT Pros & Developers. It's quick & easy.

REPOST - Please can someone help me with a simple cookie question

P: n/a
Hello,

I am having a problem setting and resetting cookies. I'm sure I just
doing something really stupid as this is such a basic issue, but I can
find any answer. Please can someone help me?

The following code is a complete page that demonstrates my problem. If
you save this as an .aspx and load it in a browser, it tells you it is
creating the cookie. If you reload the page, it tells you it is changing
the value. If you reload it again, it tells you it is removing the
cookie.

All of this is exactly what I expected, except that it didn't work. If
you close the browser window at any stage and reload the page, it always
shows the "creating" message. So, it seems that it's not actually
creating the cookie at all.

Please can someone help me here. I've spent hours trying to solve what
should be a really simple problem. TIA
<%@ Page Language="C#" Debug="true" %>
<script runat="server">

void Page_Load(Object o, EventArgs e) {
string cookieName = "fred";
if (Request.Cookies[cookieName] == null) {
// the cookie does not exist. Create it
x.Text = "Creating a new cookie";
HttpCookie cookie = new HttpCookie(cookieName, "newcookie");
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
} else if (Request.Cookies[cookieName].Value == "newcookie") {
// the cookie was created last time this page was called
x.Text = "Changing value from " + Request.Cookies[cookieName].Value
+ " to oldcookie";
Response.Cookies[cookieName].Value = "oldcookie";
} else {
// the cookie was created before the previous call to this page.
Delete it
x.Text = "Removing the cookie whose value is " +
Request.Cookies[cookieName].Value;
Response.Cookies.Remove(cookieName);
}
}

</script>

<html>
<body>
<asp:Literal ID="x" EnableViewState="false" RunAt="server" />
</body>
</html>
--
Alan Silver
(anything added below this line is nothing to do with me)
Nov 19 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.