Article

Read, Write (Create) and Remove (Delete) Cookies in Asp.Net C# with example

19 Jun 2018 Kamal Pratap
0 Comments 750 Views



Cookies is a small piece of data stored on the client machine. We use cookies to store user information like Username, Password, Email and PhoneNo etc on client machines.

 

Today we explain how to create, read and delete cookies in Asp.Net C#.

Advantages of Cookie:

  • Its clear text so user can able to read it.
  • We can store user preference information on the client machine.
  • Its easy way to maintain.
  • Fast accessing.

Disadvantages of Cookie

  • If user clear cookie information we can't get it back.
  • No security.
  • Each request will have cookie information with page.

Example :

Aspx page snippet

 Enter Name : <asp:TextBox ID="txtName" runat="server" />
 <br />
 <br />
 Your Name : <asp:Label ID="lblName" runat="server"></asp:Label>
 <br />
 <br />
 <asp:Button ID="btnCreate" Text="Create Cookie" runat="server" OnClick="btnCreate_Click" />
 <asp:Button ID="btnRead" Text="Read Cookie" runat="server" OnClick="btnRead_Click" />
 <asp:Button ID="btnDelete" Text="Delete Cookie" runat="server" OnClick="btnDelete_Click" />

Create cookies on create button click

protected void btnCreate_Click(object sender, EventArgs e)
{
    //Create a Cookie with a suitable Key.
    HttpCookie nameCookie = new HttpCookie("Name");

    //Set the Cookie value.
    nameCookie.Values["Name"] = txtName.Text;

    //Set the Expiry date.
    nameCookie.Expires = DateTime.Now.AddDays(30);

    //Add the Cookie to Browser.
    Response.Cookies.Add(nameCookie);

    txtName.Text = "";
    lblName.Text = "";
}

Read cookies on read button click

protected void btnRead_Click(object sender, EventArgs e)
{
    //Fetch the Cookie using its Key.
    HttpCookie nameCookie = Request.Cookies["Name"];

    //If Cookie exists fetch its value.
    string name = nameCookie != null ? nameCookie.Value.Split('=')[1] : "undefined";
    lblName.Text = name;
}

Delete cookies on delete button click

protected void btnDelete_Click(object sender, EventArgs e)
{
    //Fetch the Cookie using its Key.
    HttpCookie nameCookie = Request.Cookies["Name"];

    //Set the Expiry date to past date.
    nameCookie.Expires = DateTime.Now.AddDays(-1);

    //Update the Cookie in Browser.
    Response.Cookies.Add(nameCookie);

    txtName.Text = "";
    lblName.Text = "";
}

 

Kamal Pratap

I have 6+ years experience in .Net technologies like Asp.Net, C#, WCF, Web Services, SQL Server, Ajax, LinQ. Currently I am working in Netcarrots Loyalty Services as a Software Developer.

Comments

No coments found to display!

Leave a Comment