Thursday, February 25, 2010

ASP.NET C# : Working With Cookies

If enabled on client browsers, cookies are a great way to store bits of data for use by websites like remembering the login state of users who doesn't want to retype their username and password everytime they visit the site.


Here are the most common functions you can use to manipulate cookies in ASP.NET (C#):


SETCOOKIE
public void SetCookie(string name, string value, int expiration)
{
    HttpCookie cookie;
    if (Request.Cookies[name] == null) cookie = new HttpCookie(name);
    else cookie = Request.Cookies[name];
    cookie.Value = value;
    cookie.Expires = DateTime.Now.AddDays(expiration);
    Response.Cookies.Add(cookie);
}


SetCookie can be used to add a new cookie or overwrite an exisiting one in your cookie collection. Simply pass the name and value pair and the expiration (in days) for how long you want that cookie to be in use by your website. In the following code, we store the username "abby" in our collection for 1 day.


SetCookie("username", "abby", 1);


Take note though that if you use the same cookie name "username" again to set another value, it will overwrite the previous one.


GETCOOKIE
public string GetCookie(string name)
{
    HttpCookie cookie = Request.Cookies[name];
    if (cookie == null) return "";
    else return cookie.Value;
}


GetCookie can be used to retrieve the value of the cookie by passing the name. In the following code, we get the value of the cookie considering it has not yet expired.


string str = GetCookie("username");


DELETECOOKIE
public void DeleteCookie(string name)
{
    HttpCookie cookie;
    if (Request.Cookies[name] == null) return;
    else cookie = Request.Cookies[name];
    cookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(cookie);
}


DeleteCookie can be used to delete a particular cookie from the cookie collection by passing the name. Notice the -1 in the AddDays? That will simply delete the value in the physical cookie file. In the following code, we delete the "username" cookie.


DeleteCookie("username");


CLEARCOOKIES
public void ClearCookies()
{
    int cookieCount = Request.Cookies.Count;


    for (int i = 0; i < cookieCount; i++)
    {
        HttpCookie cookie = Request.Cookies[i];
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie);
    }
}


ClearCookies can be used to delete all cookies in the cookie collection. We also used the -1 in the AddDays here but used a loop to delete each one in the collection. In the following code, it will delete the physical cookie file of your website.


ClearCookies();






And that's it for cookies.


-k

2 comments: