In ASP.NET, cookies are small pieces of data that are stored on the client's computer. They are commonly used to store information about the user's session, preferences, or any other data that needs to be remembered between requests.
Setting Cookies: The server sends a Set-Cookie
header with the HTTP response, containing the name and value of the cookie, along with optional attributes like expiration time, domain, and path.
Sending Cookies: The client (browser) includes the cookies in subsequent requests to the same domain. Cookies are sent in the Cookie
header of the HTTP request.
Let's create a simple ASP.NET web application that demonstrates how to set and read cookies.
Setting a Cookie:
Example
// Set a cookie with name "username" and value "JohnDoe"
HttpCookie cookie = new HttpCookie("username", "JohnDoe");
// Set the expiration time to one day from now
cookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie to the response
Response.Cookies.Add(cookie);
Example
// Check if the "username" cookie exists
if (Request.Cookies["username"] != null)
{
// Retrieve the value of the "username" cookie
string username = Request.Cookies["username"].Value;
// Use the username as needed
}
else
{
// Cookie doesn't exist or has expired
}
Let's create a simple ASP.NET web form that sets a cookie when a button is clicked and reads the cookie value.
Default.aspx:
Example
<!DOCTYPE html>
<html>
<head runat="server">
<title>Cookie Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSetCookie" runat="server" Text="Set Cookie" OnClick="btnSetCookie_Click" />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
Example
using System;
namespace YourNamespace
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Optional: code to execute when the page loads
}
protected void btnSetCookie_Click(object sender, EventArgs e)
{
// Set a cookie with name "username" and value "JohnDoe"
HttpCookie cookie = new HttpCookie("username", "JohnDoe");
// Set the expiration time to one day from now
cookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie to the response
Response.Cookies.Add(cookie);
lblMessage.Text = "Cookie has been set.";
}
}
}
In this example, when the button btnSetCookie
is clicked, a cookie named "username" with the value "JohnDoe" is set. On subsequent visits to the page, if the cookie exists, its value is retrieved and displayed.
This demonstrates a simple use case of cookies in an ASP.NET web application. Cookies can be used for various purposes, such as remembering user preferences, session management, tracking user behavior, etc.