Introduction of Cookie in ASP.NET

Cookie is the small text file which is stored on client machine. It uses to store the small amount of information on client.
Cookie consists of the following two parts:

  1. Key - Name of Cookie.
  2. Value - Information stored in the cookie.

We also can specify the life of a cookie, if you don’t specify the life of a cookie, then it will last on the client machine till you don’t clean it.

We can specify the particular date and time when the cookie is automatically removed from the client machine.

Cookie are used to transfer the information from one page to another page. You can also disable the cookie on the browser so that the information didn’t store on your machine.

Syntax of creating cookie:

    HTTP Cookie V = new HTTP Cookie(“user”,”ABC”);

Here,

V - Cookie Object
User - Name of the Cookie [Key]
ABC - Value of the Cookie

Here is the code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class _Default : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.   
  13.     }  
  14.     protected void Button1_Click(object sender, EventArgs e)  
  15.     {  
  16.         HttpCookie v = new HttpCookie("user");  
  17.         v.Value = "abc";  
  18.         v.Expires = DateTime.Now.AddDays(30);  
  19.         Response.Cookies.Add(v);  
  20.         Response.Redirect(@"~/Default2.aspx");  
  21.     }  
  22. }  
Output:

Output