Wednesday 3 April 2013

Cookies in ASP.Net

Cookies in ASP.Net


Cookie is a small text file sent by web server and saved by web browser on client machine. Cookies are created when a user's browser loads a particular website. The website sends information to the browser which then creates a text file. Every time the user goes back to the same website, the browser retrieves and sends this file to the website's server.
There are two types of cookies available in .Net
  1. Non Persistent / Session Cookies
  2. Persistent Cookies

Non Persistent / Session Cookies

Non Persistent cookies are stored in memory of the client browser session, when browsed is closed the non persistent cookies are lost.

Persistent Cookies

Persistent Cookies have an expiration date and theses cookies are stored in Client hard drive.
Example:
Following example will show how to store the Cookies and Retrieve Cookies Data.
1.      Create the UI in ASP.Net as shown bellow

Cookies in ASP.Net

2.      Now, switch to Code View and write the following codes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
  
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    //Storing the Cookies
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Creating Object for HttpCookie Class and Named it "UserInfo"
        HttpCookie objCookie = new HttpCookie("UserInfo");

        objCookie["UserName"] = TextBox1.Text.ToString();
        objCookie["Password"] = TextBox2.Text.ToString();
        //Specified time limit for cookie to accessed
        objCookie.Expires = DateTime.Now.AddMinutes(30);

        Response.Cookies.Add(objCookie);
    }

    //Reading data from Cookies
    protected void Button2_Click(object sender, EventArgs e)
    {
       
        HttpCookie objRequestRead = Request.Cookies["UserInfo"];
        if (objRequestRead != null)
            Response.Write(objRequestRead["UserName"] + " " + objRequestRead["password"]);
        else
        {
            Response.Write("Cookies has been Expired");
            return;
        }

    }

    //Reading all stored cookies
    protected void Button3_Click(object sender, EventArgs e)
    {
        HttpCookieCollection objAllRequestRead = Request.Cookies;
        for (int i = 0; i < objAllRequestRead.Count; i++)
        {
            HttpCookie ck = objAllRequestRead.Get(i);
            if (ck != null)
            {
                Response.Write("Cookie Name "+"'" + ck.Name +"'");
                Response.Write("<br> Cookie Value " + ck.Value);
                Response.Write("<br>");
           }
        }
    }
}

Cookies are stored for 24 hrs, if you have not specified any time limit for Cookies Expiration.

No comments:

Post a Comment