C # Cookie Programming

Source: Internet
Author: User

Cookie, he first appeared in Netscape Navigator 2.0. A cookie is actually a file created by a Web server that stores information on a computer. So why does the Web server create such a file on the client? This is because when the client sends a request to the Web server, such as when it is ready to browse the page, regardless of the client.

Whether it is the first visit, the server treats it as the first time, and the Web server does the work simply by responding and then shutting down the connection to that user. The drawbacks of this process are obvious. Since Netscape has developed a cookie, it is possible to use cookies to store user identification information. The purpose of a cookie is to record the pages you have visited on that site, thus helping you customize the view the next time you visit the site. Cookies can also store personally identifiable information. Personally identifiable information is information that can be used to identify or contact you, such as your name, email address, home or work address, or phone number. However, the site can only access the personally identifiable information that you provide. For example, unless you provide an e-mail name, the site will not be able to determine your e-mail name. In addition, the website cannot access other information on the computer through cookies. Unless, of course, you provide. So where exactly is the cookie stored? If the machine's system is Windows 98 and installed in the "C" disk, then the cookie is stored in the "c:windowscookies" directory, and if the machine system is Windows 2000 and is installed in "C" disk, then the cookie is stored in "c:documents and Settingsadministratorcookies "in the directory. Having learned so much about cookies, let's take a look at the focus of this article-how C # is programmed in cookie terms. The main contents are two points: one is how C # writes cookies, and the other is how C # accesses its own written cookies.

The software Environment of program design and operation introduced in this paper:


Microsoft Corporation Windows 2000 Server Edition
. Net FrameWork SDK Beta 2


C # 's cookie-related programming is done through an ASP.

Second, how C # writes cookies:

In order to write a cookie, his steps are mainly three-step, as follows:


The first thing to do is create a HttpCookie object that constructs a cookie with the name of the cookie that will be generated later. The following code is specific:
HttpCookie cookie = new HttpCookie ("User-defined cookie name");

Then assign a string value to the "value" property of the created HttpCookie object, and the value of "value" is the value of the cookie that is subsequently generated. The specific code is as follows:
Cookies. Value = "The user assigns a value to the cookie"; If the value of the cookie you want to write is not a simple string, but rather a complex data type, we know that these data types cannot be stored directly into a cookie because the cookie can only store strings. But you can do this by converting this complex data type into multiple strings and assigning the multiple strings to the resulting cookie value so that the content in the cookie is rich and the functionality of the cookie is powerful. At this point you may understand why when you browse the Web server, the Web server will know when you've browsed, and have spent too much time waiting for information. Because this information is stored in the cookie that was generated by the Web server the first time you browsed the page. The following code is an example of storing multiple strings to a cookie:
Cookie ["name"] = "Wang Tian";
Cookie ["gender"] = "male";
Cookie ["age"] = "26";

Cookies are temporary and permanent. Persistent cookies are stored on your computer as files and remain on your computer when you turn off Internet Explorer. When you visit the site again, the Web site where the Cookie was created can be read. In the specific programming time, when writing this cookie, set the life cycle of the cookie, the following code:
DateTime dtmnow = new DateTime ();
Dtmnow = DateTime.Now;
TimeSpan Tmspminute = new TimeSpan (0, 0, 30, 0, 0);

The above code is set to produce a cookie with a lifetime of "30 minutes" and you can modify the "TimeSpan" attribute to set the specific lifetime of the cookie being generated.
Finally, the "Add ()" Method of the "Response.Cookies" object is called to add this object so that a cookie can be generated. The specific code is as follows:
Response. Cookies. ADD (cookie);
The following code is the complete code for writing cookies in C # (write.aspx): <% @ language = "C #"%>



Create a cookie in a C # page
The life cycle of this cookie is defined as one hours

is the interface after the above code is run:

Figure 01:c# Program run interface for writing cookies


Of course, the above code produces a cookie that is a bit monotonous on the content. In fact, for a very rich cookie, he has many attributes that make full use of these attributes to take advantage of the powerful features of cookies. The following table is some of the common properties of cookies:

Property Description
Domain setting/Obtaining the name of the cookie to which it belongs. Once this attribute is set, only Web servers that are limited to this domain name can access this cookie. Can be set to "ccw.com.cn"
Path Sets/Gets the paths that the cookie should belong to, and if set, the Web page that accesses the cookie is limited to this path. Web pages for other paths are not accessible.
Secure Sets/obtains an identity that indicates whether the HTTP protocol can safely transmit cookies to the client's browser.
HasKeys Indicates whether this cookie is composed of multiple strings.


When writing cookies, maximizing the use of these attributes is important for maximizing the amount of cookies written.

C # is how to read a cookie that has been generated:

It is much easier to read a specified cookie than to write a cookie, just use the "Request.Cookies" object to complete it. Here's how to read the specified cookie name:

HttpCookie cookie = request.cookies [the name of the cookie];

Here are the values that show the cookie that has been read:

Response.Write (Cookies. Value. ToString ()); Mastering the above points, reading the cookie is very easy, the following is the program code to read the cookie (read.aspx): <% @ language = "C #"%>



Read the specified cookie value in the C # page

4. Modify and delete cookies

Modify Cookies

Cookies cannot be modified directly.
The process of changing a cookie involves creating a new cookie with a new value.
It is then sent to the browser to overwrite the old version of the Cookie on the client.

Delete Cookies

Deleting a cookie (that is, physically removing a cookie from the user's hard drive) is a form of a cookie modification.
Because the Cookie is on the user's computer, it cannot be removed directly.
However, you can have your browser delete cookies for you.
The technique is to create a new cookie with the same name as the cookie to be deleted.
and set the expiration date of the Cookie to a date that is earlier than the current date.
When the browser checks the expiration date of the cookie, the browser discards the now-expired cookie.
The following code example demonstrates one way to remove all cookies available in an application:

Copy C # code save code
HttpCookie Acookie;
String CookieName;
int limit = Request.Cookies.Count;
for (int i = 0; i < limit; i++)
{
CookieName = Request.cookies[i]. Name;
Acookie = new HttpCookie (cookiename);
Acookie.expires = DateTime.Now.AddDays (-1);
RESPONSE.COOKIES.ADD (Acookie);
}

C # Cookie Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.