2012-06-15

How to set/retrieve/remove cookies from C#

To set Cookies, use the following code.

HttpCookie cookie = new HttpCookie("CookieName");
cookie["CookieName"] = Your_value_here;
cookie.Expires = DateTime.Now.AddDays(90d); //It will set the cookie for about 3 months.
Response.Cookies.Add(cookie);

To get the Cookies,

string cookieValue;
if (HttpContext.Current.Request.Cookies["CookieName"] != null)
cookieValue = HttpContext.Current.Request.Cookies["CookieName"];

To clear the Cookies,

HttpContext.Current.Response.Cookies["CookieName"].Expires = DateTime.Now.AddDays(-1d);

No comments: