JasonBie

Cookie

Before you can use cookies, you should import the System.Net namespace so you can easily work with the appropriate types: 
using System.Net; 

 

Cookies are fairly easy to use. Both the Request and Response objects (which are provided through Page properties) provide a Cookies collection. The important trick to remember is that you retrieve cookies from the Request object, and you set cookies using the Response object. 
To set a cookie, just create a new HttpCookie object. You can then fill it with string information (using the familiar dictionary pattern) and  attach it to the current web response: 
// Create the cookie object. 
HttpCookie cookie = new HttpCookie("Preferences"); 
 
// Set a value in it. 
cookie["LanguagePref"] = "English"
 
// Add another value. 
cookie["Country"] = "US"
 
// Add it to the current web response. 
Response.Cookies.Add(cookie); 
 

A cookie added in this way will persist until the user closes the browser and will be sent with every request. To create a longer-lived cookie, you can set an expiration date: 

// This cookie lives for one year. 
cookie.Expires = DateTime.Now.AddYears(1); 
 

You retrieve cookies by cookie name using the Request.Cookies collection: 

HttpCookie cookie = Request.Cookies["Preferences"]; 
 
// Check to see whether a cookie was found with this name. 
// This is a good precaution to take, 
// because the user could disable cookies, 
// in which case the cookie will not exist. 
string language; 
if (cookie != null

    language = cookie["LanguagePref"]; 
 

The only way to remove a cookie is by replacing it  with a cookie that has an expiration date that has already passed. This code demonstrates the technique: 

HttpCookie cookie = new HttpCookie("Preferences"); 
cookie.Expires = DateTime.Now.AddDays(-1); 
Response.Cookies.Add(cookie); 

posted on 2012-04-12 15:24  JasonBie  阅读(153)  评论(0编辑  收藏  举报

导航