Reputation: 1
I'm having trouble overwriting the value of a cookie. The first time a user submits a username the cookie stores in the browser fine and is displayed properly. But when the user tries to submit a different user name the page refreshes and the old cookie is still set. Here is my hopefully understandable code, any help is appreciated.
protected void Cookie_Encode(object sender, EventArgs e)
{
// Encoding username in Base64
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(User_box.Text);
string Encoded_user = System.Convert.ToBase64String(plainTextBytes);
// Creating and setting the cookie
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["UserName"] = Encoded_user;
myCookie.Expires = DateTime.Now.AddDays(7d);
Response.Cookies.Add(myCookie);
Response.Redirect(Request.RawUrl);
}
Upvotes: 0
Views: 75
Reputation: 1861
Use DateTime.Now.AddDays(-1)
instead of DateTime.Now.AddDays(7d)
.
protected void Cookie_Encode(object sender, EventArgs e)
{
// Encoding username in Base64
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(User_box.Text);
string Encoded_user = System.Convert.ToBase64String(plainTextBytes);
// Creating and setting the cookie
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["UserName"] = Encoded_user;
myCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie);
Response.Redirect(Request.RawUrl);
}
Upvotes: 1