๐ช 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
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 :