Table of contents
1.
Introduction
2.
ASP.NET Cookies
2.1.
Cookie's Common Properties
2.2.
Advantages of Cookie
2.3.
Disadvantages of Cookie
2.4.
Ways to Store ASP.NET Cookies
3.
HttpCookie Example
4.
Cookie Collection Example
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

ASP.NET Cookies

Author Abhay Trivedi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

ASP.NET Cookie is a tiny bit of text used to store user-specific information. The web application can read this information whenever a user visits the site.

When a request comes for a web page, the web server sends a page and a cookie containing the date and time. This stores cookie in a folder on the user's hard disk.

When a request comes for a web page again, the browser looks on the user's hard drive for the cookie associated with a web page. Browser stores separate cookies for each different sites user visits.

In this blog, we will go through the concepts of ASP.NET Cookies in detail.

ASP.NET Cookies

The ASP.NET Cookies is small in size and can store only 4 KB (4096 Bytes) text, and are of two types.

  • Persist Cookie - A cookie that has not expired is called a Persist Cookie.
  • Non-Persist Cookie - A cookie has expired, called a Non-Persist Cookie.

Cookie's Common Properties

  • Domain: We use it to associate cookies to the domain.
  • Secure: We can enable the secure cookie to set valid (HTTP's).
  • Value: We can manipulate individual cookies.
  • Values: We can influence cookies with key/value pairs.
  • Expires: We use it to set expiration dates for the cookies.

Advantages of Cookie

  • Its clear text so users can able to read it.
  • It can store users' preference information on the client machine.
  • It's an easy way to maintain.
  • Fast accessing.

Disadvantages of Cookie

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

Ways to Store ASP.NET Cookies

There are two ways to store ASP.NET cookies in the application.

  • Cookies collection
  • HttpCookie

We can add cookies either to the ASP.NET Cookies collection or by creating an instance of HttpCookie class. Both work the same except that HttpCookie requires Cookie name as part of the constructor.

Also see, .Net

HttpCookie Example

Here we are creating and adding cookies with the help of HttpCookie class.

// HttpCookieExample.aspx

<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="HttpCookieExample.aspx.cs" Inherits="CookieExample.HttpCookieExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form" runat="server">
        <div>
            <asp:Label ID="LabelID" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>

 

// HttpCookieExample.aspx.cs

using System;
using System.Web;
namespace WebFormsControlls
{
    public partial class HttpCookieExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Creating Cookie
            HttpCookie cookieObj = new HttpCookie("student");
            cookieObj.Value = "Chunky Panday";
            Response.Cookies.Add(cookieObj);
    
            // Fetching Cookie
            var cookieVal  = Response.Cookies["student"].Value;
            LabelID.Text = cookieVal;
        }
    }
}

 

Output:

Cookie Collection Example

In the following example of a fruit basket, we add cookies directly to the ASP.NET Cookies collection.

// CookieCollectionExample.aspx

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="CookieCollectionExample.aspx.cs"
Inherits="CookieExample._CookieCollectionExample" %>
<form id="form1" runat="server">
    <asp:Label ID="TopLabel" runat="server" Text="Select Fruit Preferences:"></asp:Label>
    <br />
    <br />
    <asp:CheckBox ID="apple" runat="server" Text="Apple" />
    <br />
    <asp:CheckBox ID="orange" runat="server" Text="Orange" />
    <br />
    <asp:CheckBox ID="guava" runat="server" Text="Guava" />
    <br />
    <asp:CheckBox ID="kiwi" runat="server" Text="Kiwi" />
    <br />
    <asp:CheckBox ID="banana" runat="server" Text="Banana" />
    <br />
    <asp:CheckBox ID="strawberry" runat="server" Text="Strawberry" />
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" OnClick="Submit_Button" Text="Submit" />
    <p>
        <asp:Label ID="ChoiceLabel" runat="server"></asp:Label>
    </p>
</form>

 

// CookieCollectionExample.aspx.cs

using System;  
using System.Web.UI;  
namespace CookieExample  
{  
    public partial class _CookieCollectionExample : Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            // Setting expiry date & time of the cookies  
            Response.Cookies["basket"].Expires = DateTime.Now.AddDays(-1);  
        }  
        protected void Submit_Button(object sender, EventArgs e)  
        {  
            ChoiceLabel.Text = "";  
            // Creating Cookies
            if (apple.Checked)  
                Response.Cookies["basket"]["apple"]  = "apple";  
            if (orange.Checked)  
                Response.Cookies["basket"]["orange"]   = "orange";  
            if (guava.Checked)  
                Response.Cookies["basket"]["guava"] = "guava";  
            if (kiwi.Checked)  
                Response.Cookies["basket"]["kiwi"]   = "kiwi";  
            if (banana.Checked)  
                Response.Cookies["basket"]["banana"]   = "banana";  
            if (strawberry.Checked)  
                Response.Cookies["basket"]["strawberry"]  = "strawberry";  
            
            // Fetching Cookies
            if (Request.Cookies["basket"].Values.ToString() != null)
            {
                if (Request.Cookies["basket"]["apple"] != null)
                    ChoiceLabel.Text += Request.Cookies["basket"]["apple"] + " ";
                if (Request.Cookies["basket"]["orange"] != null)
                    ChoiceLabel.Text += Request.Cookies["basket"]["orange"] + " ";
                if (Request.Cookies["basket"]["guava"] != null)
                    ChoiceLabel.Text += Request.Cookies["basket"]["guava"] + " ";
                if (Request.Cookies["basket"]["kiwi"] != null)
                    ChoiceLabel.Text += Request.Cookies["basket"]["kiwi"] + " ";
                if (Request.Cookies["basket"]["banana"] != null)
                    ChoiceLabel.Text += Request.Cookies["basket"]["banana"] + " ";
                if (Request.Cookies["basket"]["strawberry"] != null)
                    ChoiceLabel.Text += Request.Cookies["basket"]["strawberry"] + " ";
            }else ChoiceLabel.Text = "Please select your choice";
            Response.Cookies["basket"].Expires = DateTime.Now.AddDays(-1);
        }
    }
}

 

Output:

Ideal:

On Submission:

FAQs

  1. What is ASP.NET?
    ASP.NET is an open-source, server-side web development framework designed to produce dynamic web pages. Microsoft developed it to allow programmers to build active websites, applications, and services.
     
  2. What is ASP.NET in C#?
    ASP.NET is a web-based application framework developed and marketed by Microsoft to let programmers build dynamic websites. It will enable you to use a full-featured programming language such as C# or VB.NET to build web applications quickly.
     
  3. What is the difference between ASP.NET and C#?
    The difference between ASP.NET and C# is that ASP.NET is an open-source framework for web application development to create dynamic content over web pages. C# is an object-oriented, functional, generic, imperative, and component-based programming language.
     
  4. What are ASP.NET Cookies?
    ASP.NET Cookies are text files with small data like a username and password to identify a computer as you use a computer network. Specific cookies known as HTTP cookies identify particular users and improve your web browsing experience.
     
  5. How to clear the cookie information?
    We can clear cookie information from the client machine on the cookie folder. Set expires to cookie object like:
userInfo.Expires = DateTime.Now.AddHours(1);

    It will clear the cookie within an hour.

Key Takeaways

This article teaches about ASP.NET Cookies and how we use them. We saw why ASP.NET Cookies could be beneficial for a developer to learn. 

Click here to read about the Top 10 web development frameworks. Apart from this, you can also expand your knowledge by referring to these articles on Features Of ASP Net and ASP Full Form. Check out our Web development course and blogs on Backend Web Technologies.

If you are preparing for your DSA interviews then, Coding Ninjas Studio is a one-stop destination. This platform will help you acquire effective coding techniques and overview student interview experience in various product-based companies.

Happy Learning!

Live masterclass