03 April 2014

Cookies in ASP.Net C#

In this article, I’m trying to explain how to read and write cookies in asp.net
Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.
Cookies may be used for authentication, identification of a user session, user's preferences, shopping cart contents, or anything else that can be accomplished through storing text data. Cookies can also be used for travelling of data from one page to another.

Type of Cookies?

  1. Persist Cookie - A cookie has not have expired time Which is called as Persist Cookie
  2. Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie

Example

 

Step 1:-

Design the form as shown below:
Cookies in ASP.Net C#
 

Step 2:-

Write the code in the .aspx.cs file
using System;
using System.Web;
 
namespace CookiesWebApplication
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            HttpCookie objCookie = new HttpCookie("UserInfo");
 
            objCookie["UserName"] = txtUsername.Text.ToString();
            objCookie["Password"] = txtPassword.Text.ToString();
            objCookie.Expires = DateTime.Now.AddMinutes(30);
 
            Response.Cookies.Add(objCookie);
 
            txtUsername.Text = "";
            txtPassword.Text = "";
 
        }
 
        protected void btnRead_Click(object sender, EventArgs e)
        {
            HttpCookie objRequestRead = Request.Cookies["UserInfo"];
            if (objRequestRead != null)
            {
                txtUsername.Text = objRequestRead["Username"];
                txtPassword.Text = objRequestRead["Password"];
            }
            else
            {
                Response.Write("Cookies has been Expired");
                return;
            }
        }
 
        protected void btnClear_Click(object sender, EventArgs e)
        {
            txtUsername.Text = "";
            txtPassword.Text = "";
        }
    }
}
 

 

Step 3:-

 
Cookies in ASP.Net C#
After filling the values in the textbox and click on the save button, cookie will be created on the client machine and the textboxes will be blank as shown below.
Cookies in ASP.Net C#
If you want to read the cookies, click on the read button
Cookies in ASP.Net C#
Clear button will clear the value in the textboxes.

No comments:

Post a Comment