May 30, 2009

Read n Write Cookie

A cookie can be used to store user data on the client side. Data may contain state information and user preferences. The cookie is stored as a text file on the client's system if the cookie is persistent or in browser's session's memory if the cookie is temporary. Using cookies is a handy way to store data on the client but the user, at the same time, can delete a cookie or disable cookie from the browser settings. A cookie is a better way to hold data, compared to hidden fields and query string, since the data can be stored on the client even if the client starts viewing a different page.

In Asp.Net application, a cookie can be created by adding a value to the Response.Cookies.HttpCookieCollection. Once a cookie is added, the value of the cookie can be read by using the Request.Cookies property.

In the following example, a cookie is added in the Page_Load method by adding a value to the Respose.Cookies collection and the value is read on a button click.

protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cookies["name"].Value = "shahed"; //value of cookie "name"
        Response.Cookies["name"].Domain = "localhost"; // domain for the cookie
        Response.Cookies["name"].Expires = DateTime.Now.AddDays(1);//expire date
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Request.Cookies["name"] != null)//check if cookie exist
        {
            Response.Write("Cookie name:\t" + Request.Cookies["name"].Name + "<br/>");//name of cookie
            Response.Write("Cookie Value:\t " + Request.Cookies["name"].Value + "<br/>");//value of cookie
            Response.Write("Cookie Expires:\t" + Request.Cookies["name"].Expires + "<br/>");//expiry date of cookie
            Response.Write("Cookie Domain:\t" + Request.Cookies["name"].Domain + "<br/>");//domain of cookie
        }       
    }


In Page_Load method, a cookie with name "name" is added. The expiry date is set to be one day and it is scoped for "localhost" domain. There is a button on the main which when clicked, checks if the cookie exists, and if so writes the properties of the cookie.

0 comments:

Reference: Shahed Kazi at AspNetify.com