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 Name | Purpose |
|---|---|
CookiesDemo.aspx | Web Form to set and read cookies |
CookiesDemo.aspx.cs | Code-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
| Element | What It Does |
|---|---|
txtName | Field for user to type their name |
btnSave | Triggers code to save the value in a cookie |
btnRead | Triggers code to read cookie and show greeting |
lblMessage | Displays 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 Line | What It Does |
|---|---|
new HttpCookie("UserName") | Creates a cookie named “UserName” |
userCookie.Value = txtName.Text | Stores 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
| Feature | Classic ASP | ASP.NET Web Forms |
|---|---|---|
| Set Cookie | Response.Cookies("Name") = "X" | Response.Cookies["Name"].Value = "X" |
| Get Cookie | Request.Cookies("Name") | Request.Cookies["Name"].Value |
| Expiration | Response.Cookies("X").Expires | HttpCookie.Expires = DateTime |
| Data Type | Strings only | String (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
HttpCookieclass - 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 :
