articles

Home / DeveloperSection / Articles / Cookies in ASP.Net C#

Cookies in ASP.Net C#

Sumit Kesarwani 8157 11-May-2013

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
    {
        protectedvoid Page_Load(objectsender, EventArgse)
        { 
        } 
        protectedvoid btnSave_Click(objectsender, EventArgse)
        {
            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 ="";

        }

        protectedvoid btnRead_Click(objectsender, EventArgse)
        {
            HttpCookie objRequestRead=Request.Cookies["UserInfo"];
            if (objRequestRead!=null)            {
                txtUsername.Text =objRequestRead["Username"];
                txtPassword.Text =objRequestRead["Password"];
            }

            else
            {

                Response.Write("Cookies has been Expired");
                return;

            }

        } 

        protectedvoid btnClear_Click(objectsender, EventArgse)
        {
            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.

You can also read these related post

https://www.mindstick.com/Articles/40/cookies-in-asp-dot-net



Updated 03-Mar-2020

Leave Comment

Comments

Liked By