How to Create Cookies in ASP.Net with C# ?

In this asp.net article we will learn how to use cookies in asp.net with c# language.

Here, we understand to use cookies by tacking an example.

First we create a cookies and stored it and then retrieve the cookies in asp.net web application.

What is cookies ?

– Cookies is a small pieces of information, which is stored on user local browser. it may contain username, password or any information. Cookies stored at user computer “C”\Document and Setting\Current login_User\Cookie”.

Here, we can use Response object to create a cookies.

First, Design asp.net web form like :

How to Create Cookies in ASP.Net with C#
How to Create Cookies in ASP.Net with C#

Here, we have two button control one for Create Cookies and one for Retrieve Cookies.

Write below code for Create Cookies in Button Click events.

 protected void Button1_Click(object sender, EventArgs e)
{
Response.Cookies[“MeeraAcademy”].Value = TextBox1.Text;
Response.Cookies[“MeeraAcademy”].Expires = DateTime.Now.AddMinutes(1);
}

In above code we use Response.Cookies object for create Cookies.

We store cookies values by using value property, and use Expires property for Expires Cookies.

In above example we have set 1 (one) Minute time for Expire Cookies, we can retrieve cookies values up to one minute, after one minute cookies values automatically expires.

How to Create Cookies in ASP.Net with C#
How to Create Cookies in ASP.Net with C#

write below code in Retrieve Button Click events.

protected void Button2_Click(object sender, EventArgs e)
{
if (Request.Cookies[“MeeraAcademy”] == null)
{
TextBox2.Text = “No cookie found”;
}
else
{
TextBox2.Text = Request.Cookies[“MeeraAcademy”].Value;
}
}

For Retrieve cookies we use here Request.Cookies object in asp.net.

How to Create Cookies in ASP.Net with C#
How to Create Cookies in ASP.Net with C#

Below figure shows the out put of expires cookies.

How to Create Cookies in ASP.Net with C#
How to Create Cookies in ASP.Net with C#

I hope this asp.net cookies example will help you…..

Leave a Reply

Your email address will not be published. Required fields are marked *