How do we create,Read,Delete Cookies in Asp.net


A cookie is a small bit of text file that browser creates and stores on your machine (hard drive). Cookie is a small piece of information stored as a string. Web server sends the cookie and browser stores it, next time server returns that cookie.Cookies are mostly used to store the information about the user. Cookies are stores on the client side.

Here i m going to explain you by providing example of Remember me Code :

Step 1 : if check box is checked for “Remember Me” then create cookie else Delete it.

if (chkRememberMe.Checked == true)
                    {
                        //Create Cookie to Store AdminInfo
                        HttpCookie aCookie = new HttpCookie("AdminInfo");
                        aCookie.Values["userName"] = txtUsername.Text;
                        aCookie.Values["Password"] = txtPassword.Text;
                        aCookie.Values["lastVisit"] = DateTime.Now.ToString();
                        aCookie.Expires = DateTime.Now.AddDays(10);
                        Response.Cookies.Add(aCookie);
                    }
                    else
                    {
                        //Delete Cookie
                        HttpCookie aCookie = new HttpCookie("AdminInfo");                       
                        aCookie.Expires = DateTime.Now.AddDays(-1);
                        Response.Cookies.Add(aCookie);
                    }

Step 2 : now check cookie is null or not in page load event & set username & password from cookie

protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           if (Request.Cookies["AdminInfo"] != null)
           {
               txtUsername.Text = Request.Cookies["AdminInfo"]["userName"] == null ? null : Request.Cookies["AdminInfo"]["userName"].ToString();
               string pwd = Request.Cookies["AdminInfo"]["Password"] == null ? null : Request.Cookies["AdminInfo"]["Password"].ToString();
               txtPassword.Attributes.Add("value", pwd);
           }
       }

   }

 

Technorati Tags:
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s