๐Ÿง  ASP.NET State Management & Personalization
Estimated reading: 4 minutes 32 views

๐Ÿช ASP.NET Cookies โ€“ Store User Data in Browser (with Classic ASP Comparison)

๐Ÿงฒ Introduction โ€“ What Are Cookies in ASP.NET?

Cookies are small text files saved in the userโ€™s browser to store non-sensitive information across sessions or visits. ASP.NET provides built-in support to create, read, update, and expire cookies.

Cookies are ideal for:

  • โ€œRemember meโ€ login features
  • User preferences (theme, language)
  • Persistent form values
  • Tracking returning visitors

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How cookies work in ASP.NET
  • How to create, read, and expire cookies with C#
  • Differences between ASP.NET and Classic ASP cookie handling
  • Full code examples with beginner-friendly explanations and output

๐Ÿ“‚ ASP.NET Cookie File Overview

File NamePurpose
CookiesDemo.aspxWeb Form to set and read cookies
CookiesDemo.aspx.csCode-behind with cookie logic

๐Ÿ“„ Step 1: Markup File โ€“ CookiesDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CookiesDemo.aspx.cs" Inherits="CookiesDemo.CookiesDemo" %>

<html>
<body>
  <form id="form1" runat="server">

    <h3>๐Ÿช ASP.NET Cookies Demo</h3>

    <asp:Label ID="lblPrompt" runat="server" Text="Enter your name:" /><br />
    <asp:TextBox ID="txtName" runat="server" /><br /><br />

    <asp:Button ID="btnSave" runat="server" Text="Save Cookie" OnClick="btnSave_Click" />
    <asp:Button ID="btnRead" runat="server" Text="Read Cookie" OnClick="btnRead_Click" /><br /><br />

    <asp:Label ID="lblMessage" runat="server" Font-Bold="true" ForeColor="Blue" />

  </form>
</body>
</html>

๐Ÿ” Markup Explanation

ElementWhat It Does
txtNameField for user to type their name
btnSaveTriggers code to save the value in a cookie
btnReadTriggers code to read cookie and show greeting
lblMessageDisplays message based on cookie content

โš™๏ธ Step 2: Code-Behind โ€“ CookiesDemo.aspx.cs

public partial class CookiesDemo : System.Web.UI.Page
{
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // Create new cookie
        HttpCookie userCookie = new HttpCookie("UserName");
        userCookie.Value = txtName.Text;

        // Set expiry to 7 days
        userCookie.Expires = DateTime.Now.AddDays(7);

        // Add cookie to response
        Response.Cookies.Add(userCookie);

        lblMessage.Text = "Cookie saved!";
    }

    protected void btnRead_Click(object sender, EventArgs e)
    {
        // Read cookie from request
        HttpCookie userCookie = Request.Cookies["UserName"];

        if (userCookie != null)
        {
            lblMessage.Text = "Welcome back, " + userCookie.Value + "!";
        }
        else
        {
            lblMessage.Text = "No cookie found.";
        }
    }
}

๐Ÿ” Code Explanation

Code LineWhat It Does
new HttpCookie("UserName")Creates a cookie named “UserName”
userCookie.Value = txtName.TextStores textbox input in the cookie
userCookie.Expires = DateTime.Now.AddDays(7)Sets cookie to expire in 7 days
Response.Cookies.Add(userCookie)Sends the cookie to browser
Request.Cookies["UserName"]Reads cookie from browser
if (userCookie != null)Checks if cookie exists

๐Ÿ–ฅ๏ธ Output Preview in Browser

โ–ถ๏ธ On Save:

๐Ÿช ASP.NET Cookies Demo  
Enter your name: [Vaibhav]  
[Save Cookie]  
โ†’ Cookie saved!

โ–ถ๏ธ On Read (same or later visit):

[Read Cookie]  
โ†’ Welcome back, Vaibhav!

โœ… This works even after page refresh or revisitingโ€”until the cookie expires.


๐Ÿ” Classic ASP vs ASP.NET Cookies

FeatureClassic ASPASP.NET Web Forms
Set CookieResponse.Cookies("Name") = "X"Response.Cookies["Name"].Value = "X"
Get CookieRequest.Cookies("Name")Request.Cookies["Name"].Value
ExpirationResponse.Cookies("X").ExpiresHttpCookie.Expires = DateTime
Data TypeStrings onlyString (with optional encoding)
Cookie Class?โŒ Noโœ… HttpCookie object

๐Ÿ” Security Tip

Never store sensitive data (like passwords) in cookies. Cookies are stored in plain text on the client side. Use Session for secure server-side data.


๐Ÿ“Œ Summary โ€“ Recap & Takeaways

๐Ÿ” Key Learnings:

  • ASP.NET makes cookies easy using the HttpCookie class
  • Cookies are stored in the userโ€™s browser and persist across sessions
  • You can set expiration, read on return, and delete cookies easily
  • ASP.NET offers more flexibility than Classic ASP via object-based access

โœ… Cookies are perfect for:

  • โ€œRemember Meโ€ features
  • Storing theme/language preferences
  • Recognizing returning users

โ“ Frequently Asked Questions (FAQs)


โ“ Where are cookies stored?
โœ… In the userโ€™s browser as small .txt entriesโ€”based on domain and path.


โ“ Can I store multiple values in one cookie?
โœ… Yes. You can use subkeys:

HttpCookie user = new HttpCookie("UserInfo");
user["Name"] = "Vaibhav";
user["Theme"] = "Dark";
Response.Cookies.Add(user);

โ“ How do I delete a cookie in ASP.NET?
โœ… Set its expiration date in the past:

HttpCookie expired = new HttpCookie("UserName");
expired.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(expired);

โ“ Do cookies work if the user closes their browser?
โœ… Only if an expiration date is set. Otherwise, they’re called session cookies and disappear on browser close.


Share Now :

Leave a Reply

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

Share

๐Ÿช ASP.NET โ€“ Cookies (from Classic ASP)

Or Copy Link

CONTENTS
Scroll to Top