Read cookie, if not there, create one (C#) : Read « Cookie « ASP.NET Tutorial






File: Default.ascx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="CookieExample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <div>
        <asp:Label ID="lblWelcome" runat="server" EnableViewState="False" ></asp:Label>
      </div>
      <br />
      Name:
      <asp:TextBox ID="txtName" runat="server" Width="178px"></asp:TextBox>
      <asp:Button ID="cmdStore" runat="server" OnClick="cmdStore_Click" Text="Create Cookie" />
    </div>
    </form>
</body>
</html>

File: Default.ascx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class CookieExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    HttpCookie cookie = Request.Cookies["Preferences"];
    if (cookie == null)
    {
      lblWelcome.Text = "<b>Unknown Customer</b>";
    }
    else
    {
      lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
      lblWelcome.Text += "Welcome, " + cookie["Name"];
    }

    }
  protected void cmdStore_Click(object sender, EventArgs e)
  {
    HttpCookie cookie = Request.Cookies["Preferences"];
    if (cookie == null)
    {
      cookie = new HttpCookie("Preferences");
    }

    cookie["Name"] = txtName.Text;
    cookie.Expires = DateTime.Now.AddYears(1);
    Response.Cookies.Add(cookie);

    lblWelcome.Text = "<b>Cookie Created.</b><br><br>";
    lblWelcome.Text += "New Customer: " + cookie["Name"];
  }
}








12.5.Read
12.5.1.Reading Cookies
12.5.2.List all cookies contained in the Request.Cookies collection
12.5.3.Read cookie, if not there, create one (C#)