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

A

Alan Silver

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>
 

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

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top