Cookies are used to store the information when web server and web browser are not connected. This information can be about the online visitors, total visits to that particular application etc. A cookie is used to identify a user. The cookie is a small text file that is sent by web server and saved by web browser on client machine. A cookie is also knows as Http Cookie, Session Cookie, Web Cookie etc.




Role of a Cookie in Asp.Net:

 A Cookie plays different different roles in Asp.net. It can be used to fetching user information, for User session Identification, Authorization for user session, user preferences etc.

Creating Cookies:

 There are several methods to create a Cookie in your application. We are going to discuss all these methods

Method 1: We can create a cookie by using HttpCookies Class. This class has definition in System.Web namespace:

HttpCookie empCookie = new HttpCookie("empCookie");
 empCookie.Value = txtEmpName.Text;
 empCookie.Expires = DateTime.Now.AddDays(1);
 Response.Cookies.Add(empCookie);

Method 2: Using Response.Cookies method:

 Response.Cookies["empCookie"].Value= txtEmpName.Text;
 Response.Cookies["empCookie"].Expires = DateTime.Now.AddDays(1);

Fetching Cookies Value:

 The method is same for both the above method to fetch a Cookie value.
string empname = Request.Cookies["empCookie"].value;

Deleting Cookies:

 To delete a cookie first make sure that your cookie is not null and does not contain any useful information. Remember the cookie is expired after the period of time that we give while creating the cookie.
if(Request.Cookies["empCookie"] != null)
 {
 Response.Cookies["empCookie"].Expires = DateTime.Now.AddDays(-1);
 Response.Reirect("Home.aspx") // to refresh the page
 }

Suggested entry:

1. Asp.Net Session State : Handling Session and Set Timeout for Session

2. Passing Values between Pages using QueryString

3. How to Create a Cookie that can contain multiple Values

4. Passing Data Between Two WinForms

admin (155 Posts)


One Response to ASP.NET Cookies – Creating, Retrieving and Deleting Cookies

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.