Monday, September 20, 2010

Cookies

Here are the function to add/update, remove, get cookies.

public void SetCookie(string key , string value)
{
HttpCookie myCookie = new HttpCookie(key);
//DateTime now = DateTime.Now; // Uncomment to add expiration time
// Set the cookie value.
myCookie.Value = value;
// Set the cookie expiration date.
//myCookie.Expires = now.AddDays(1); // Uncomment to add expiration time
// Add the cookie.
System.Web.HttpContext.Current.Response.Cookies.Add(myCookie);
}
public void RemoveCookie(string key)
{
if (System.Web.HttpContext.Current.Request.Cookies[key] != null)
{
HttpCookie myCookie = new HttpCookie(key);
myCookie.Expires = DateTime.Now.AddDays(-1d);
System.Web.HttpContext.Current.Response.Cookies.Add(myCookie);
}
}
public string GetCookie(string key)
{
if (System.Web.HttpContext.Current.Request.Cookies[key] != null)
return System.Web.HttpContext.Current.Request.Cookies[key].Value;
else
return "";
}

If you want to store multiple values in a single cookie, use the following functions.

public void SetCookie(string key, string value)
{
if (!System.Web.HttpContext.Current.Response.Cookies["myCookie"].HasKeys)
{
HttpCookie cookie = new HttpCookie("myCookie");
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

//cookie.Values.Add(key, value);
System.Web.HttpContext.Current.Response.Cookies["myCookie"][key] = value;
System.Web.HttpContext.Current.Response.Cookies.Add(System.Web.HttpContext.Current.Response.Cookies["myCookie"]);
}

public void RemoveCookie(string key)
{
if (System.Web.HttpContext.Current.Response.Cookies["myCookie"].HasKeys)
{
System.Web.HttpContext.Current.Response.Cookies["myCookie"].Values.Remove(key);
}
}
public string GetCookie(string key)
{
if (System.Web.HttpContext.Current.Request.Cookies["myCookie"] != null)
{
if (System.Web.HttpContext.Current.Request.Cookies["myCookie"].HasKeys)
{
return System.Web.HttpContext.Current.Request.Cookies["myCookie"][key];
}
else
{
return "";
}
}
else
{
return "";
}
}

No comments:

Post a Comment