Cookie Programming in C #

Source: Internet
Author: User

Cookies are the so-called "cookie" that 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 a client sends a request to a Web server (such as when it is ready to browse the page), the server treats it as the first time, regardless of whether the client is first visited, 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 Dtnow = DateTime. Now;
TimeSpan Tsminute = new TimeSpan (0, 1, 0, 0);
Cookies. Expires = Dtnow + Tsminute;

The above code is set to produce a cookie that has a lifetime of "one hours" 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 #"%>
<script runat = "server" >
void writeclicked (Object Sender, EventArgs e)
{
Create a HttpCookie object
HttpCookie cookie = new HttpCookie (NameField. Text);
Set this cookie value
Cookies. Value = Valuefield. Text;
Set the life cycle of the cookie, defined here as one hours
DateTime Dtnow = DateTime. Now;
TimeSpan Tsminute = new TimeSpan (0, 1, 0, 0);
Cookies. Expires = Dtnow + Tsminute;
Cookie ["name"] = "Wang Tian";
Cookie ["gender"] = "male";
Cookie ["age"] = "26";
Add this cookie
Response. Cookies. ADD (cookie);
Response. Write (NameField. Text + "Cookie creation completed &LT;BR > }
</script >
<body >

The life cycle of this cookie is defined as one hours
<form runat= "Server" >
Cookie name: <asp:textbox id = "NameField" runat = "server"/> <br >
Value of the cookie: <asp:textbox id = "Valuefield" runat = "server"/> <br >
<asp:button Text = "Create cookie" onclick = "writeclicked" runat = "server"/> <br >
</form >
</body >

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 #"%>
<script runat = "server" >
void readclicked (Object Sender, EventArgs e)
{
Get the cookie name entered by the user
String strcookiename = NameField. Text;
Get cookies
HttpCookie cookie = request.cookies [Strcookiename];
Determine if a user-entered cookie exists
if (null = = cookie) {
Response.Write ("No specified cookie <br > }
else {
Find the specified cookie and display the value of the cookie
String Strcookievalue = cookie. Value. ToString ();
Response.Write (strcookiename + "cookie value: <b >"
+ Strcookievalue + "</b > <br > }
}
</script >
<HTML >
<body >
Read the specified cookie value in the C # page <BR >
<form runat = "server" >
Please enter the cookie name to read: <asp:textbox id = "NameField" runat = "server"/>
<asp:button Text = "Read cookie" onclick = "readclicked" runat = "server"/>
</form >
</body >


is the interface after the above code is run:


Figure 02: Program run Interface for reading the value of a specified cookie


Iv. Summary:

So far, we've covered most of the cookie programming in C #. In fact, cookies on the internet have a relatively large role. For example, it allows a Web site to track the number of visits to a particular visitor, the last access time, and the path of visitors to the site, and to tell the online advertiser how many times the ad was clicked, allowing more accurate advertising; it allows users to enter sites they have browsed without typing passwords and usernames And most importantly, it can help the site to statistics user data to achieve personalized service and so on. By mastering the C # cookie programming, you can make full use of cookies in your program to implement these functions. Don't believe you have a try.

Cookie Programming in C #

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.