These 3 methods helped me persist a cookie.
Note, if the user unselects "Remember Me", you'll want to remove the cookie.
private const string RememberMeCookieName = "MyCookieName";
private string CheckForCookieUserName()
{
string returnValue = string.Empty;
HttpCookie rememberMeUserNameCookie = Request.Cookies.Get(RememberMeCookieName);
if (null != rememberMeUserNameCookie)
{
/* Note, the browser only sends the name/value to the webserver, and not the expiration date */
returnValue = rememberMeUserNameCookie.Value;
}
return returnValue;
}
private void CreateRememberMeCookie(string userName)
{
HttpCookie rememberMeCookie = new HttpCookie(RememberMeCookieName, userName);
rememberMeCookie.Expires = DateTime.MaxValue;
Response.SetCookie(rememberMeCookie);
}
private void RemoveRememberMeCookie()
{
/* k1ll the cookie ! */
HttpCookie rememberMeUserNameCookie = Request.Cookies[RememberMeCookieName];
if (null != rememberMeUserNameCookie)
{
Response.Cookies.Remove(RememberMeCookieName);
rememberMeUserNameCookie.Expires = DateTime.Now.AddYears(-1);
rememberMeUserNameCookie.Value = null;
Response.SetCookie(rememberMeUserNameCookie);
}
}