Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Setting and getting cookies
Message
 
To
12/09/2003 13:28:30
Jerry Tovar
Dana Corporation Dana It
Maumee, Ohio, United States
General information
Forum:
ASP.NET
Category:
Other
Miscellaneous
Thread ID:
00828593
Message ID:
00828727
Views:
15
Hi Jerry.

To store a cookie on the client' s machine, follow these steps:

1. Check whether the client supports cookies by using the Browser object' s Cookies property.

2. If the client supports cookies, check whether the cookie already exists by using the Request object' s Cookies collection.

3. If the cookie does not already exist, create a new cookie object using the ­HttpCookie class.

4. Set the cookie object' s Value and Expiration properties.

5. Add the cookie object to the Response object' s Cookies collection.

Here is some sample code:
private void Page_Load(object sender, System.EventArgs e)
{
      // (1) Check if browser accepts cookies.
      if (Request.Browser.Cookies)
      {
           // (2) If the cookie does not exist...
           if (Request.Cookies["LastVisit"] == null)
           {
              // (3) Create cookie.
               HttpCookie cookLastVisit = new HttpCookie("LastVisit", 
               DateTime.Now.ToString());
               // (4) Set the expiration to tommorrow.
               cookLastVisit.Expires = DateTime.Now.AddDays(1);
               // (5) Add to cookies collection.
               Response.Cookies.Add(cookLastVisit);
               // Display message.
               Response.Write("This is your first visit.");
           }
           else
           {
               // Get the cookie.
               HttpCookie cookLastVisit = Request.Cookies["LastVisit1"];
               // Display a message showing time of last visit.
               Response.Write("You last visited this page: " +
                 cookLastVisit.Value);
               // Update the cookie on the client.
               Response.Cookies["LastVisit"].Value = 
                 DateTime.Now.ToString();
               Response.Cookies["LastVisit"].Expires = 
                 DateTime.Now.AddDays(1);
           }
}
else
{
           Response.Write("Your browser does not accept cookies.");
      }
}
>Using ASP.Net and C#, how do you get and set cookie values in a ASP.Net Webform?
>
>Thanks,
>
>Jerry
-----------------------------------------

Cathi Gero, CPA
Prenia Software & Consulting Services
Microsoft C# / .NET MVP
Mere Mortals for .NET MVP
cgero@prenia.com
www.prenia.com
Weblog: blogs.prenia.com/cathi
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform