C # edit cookie

Source: Internet
Author: User

Cookie programming in C #

Cookies are called "cookies". They first appeared in Netscape Navigator 2.0. Cookies are actually files created by Web servers that store information on computers. So why does the Web server need to create such a file on the client? This is because when a client sends a request to the Web server (for example, when you are preparing to browse the page), the server treats the client as the first time whether it is the first visit, the Web server simply responds and closes the connection to the user. The shortcomings brought about by this process are obvious. Since Netscape developed a cookie, it can be used to store user identification information. The role of cookie can record the pages you have visited on the site, so that you can customize the viewing when you visit the site next time. Cookies can also store personal identifiable information. Personal identifiable information can be used to identify or contact you, such as name, email address, home or work address, or phone number. However, the website can only access the personal identifiable information you provide. For example, the website cannot determine your email name unless you provide an email name. In addition, the website cannot use cookies to access other information on the computer. Unless you provide. So where is the cookie stored? If Windows 98 is installed on the "c" drive, the cookies are stored in the "C: \ WINDOWS \ cookies" directory; if Windows 2000 is installed on the "c" drive, the cookies are stored in the "C: \ Documents ents and Settings \ Administrator \ cookies" directory. After learning so much about cookies, let's take a look at the focus of this article-How C # program cookies. The main content is as follows: C # is how to write cookies, and C # is how to access the cookies written by itself.

I. IntroductionProgramDesign and run the software environment:

    1. Microsoft Windows 2000 Server Edition
    2. . NET Framework SDK beta 2

C # cookie programming is implemented through ASP. NET pages.

II. C # How to Write cookies:

To write a cookie, follow these steps:

  1. Create an httpcookie object to construct a cookie. The object name is the cookie name generated later. The details are as follows:Code:
    Httpcookie = new httpcookie ("user-defined cookie name ");
  2. Then, assign a string value to the "value" attribute of the created httpcookie object. The "value" value is the value of the cookie generated later. The Code is as follows:
    Cookie. value = "the user assigns a value to the cookie"; if the cookie value you want to write is not a simple string, but a complex data type, we know that these data types cannot be directly stored in cookies, because they can only store strings. However, you can use a work und to convert the complex data type into multiple strings, and assign these strings to the generated cookie values at the same time, in this way, the content in cookies is enriched, and the functions completed by using cookies are also powerful in the future. At this time, you may understand why when you browse the Web server, the web server will know when you have browsed and waited for too long. Because the information has been stored in the cookie generated by the Web server when you first browsed the page. The following code stores multiple strings into cookies:
    Cookie ["name"] = "Wang Tian ";
    Cookie ["gender"] = "male ";
    Cookie ["Age"] = "26"; the cookie is temporary and permanent. Permanent cookies are stored on the computer as files, and are retained on the computer when Internet Explorer is disabled. When you access the site again, the website that creates the cookie can read it. During specific programming, the lifecycle of the cookie is set when the cookie is written. The specific code is as follows:
    Datetime dtnow = datetime. now;
    Timespan tsminute = new timespan (0, 1, 0, 0 );
    Cookie. expires = dtnow + tsminute; the above Code sets the life cycle of the generated cookie to "One Hour". You can modify the "timespan" attribute to set the specific life cycle of the generated cookie.
  3. Finally, call the "add ()" method of the "response. Cookies" object to add this object, so that a cookie can be generated. The Code is as follows:
    Response. Cookies. Add (cookie );
    The following code is the complete code (write. aspx) for writing cookies in C ):
    <% @ Language = "C #" %>
    <SCRIPT runat = "server">
    Void writeclicked (Object sender, eventargs E)
    {
    // Create an httpcookie object
    Httpcookie cookie = new httpcookie (namefield. Text );
    // Set this cookie value
    Cookie. value = valuefield. text;
    // Set the cookie lifecycle, which is defined as an hour
    Datetime dtnow = datetime. now;
    Timespan tsminute = new timespan (0, 1, 0, 0 );
    Cookie. 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 created <br> <HR> ");
    }
    </SCRIPT>
    <HTML>
    <Body>
    <H3> Create a cookie on the C # page The cookie lifecycle is defined as one hour.
    <Form runat = "server">
    Cookie name: <asp: textbox id = "namefield" runat = "server"/> <br>
    Cookie value: <asp: textbox id = "valuefield" runat = "server"/> <br>
    <Asp: button text = "create cookie" onclick = "writeclicked" runat = "server"/> <br>
    </Form>
    </Body>
    </Html>

Is the interface after the code is run:


Figure 01: C # program running interface for writing cookies

Of course, the cookie generated by the above Code is a bit monotonous on the content. In fact, for cookies with rich content, there are many other attributes that can be used to make full use of these attributes. The following table lists common attributes of cookies:


Attribute description domain: Set/obtain the domain name to which the cookie belongs. Once this attribute is set, only the Web server of this domain name can access this cookie. You can set it to "ccw.com.cn" path to set/obtain the path to which the cookie belongs. If so, the web page that accesses the cookie is limited to this path. Web pages in other paths cannot be accessed. Secure sets/gets an identifier to indicate whether the cookie can be securely transmitted to the client browser using the HTTP protocol. Haskeys indicates whether the cookie is composed of multiple strings.

When writing cookies, it is very important to use these attributes to the maximum extent possible.

3. C # How to read generated cookies:

Reading a specified cookie is much easier than writing a cookie. You only need to use the "request. Cookies" object. The following method reads the specified cookie Name:

Httpcookie cookie = request. Cookies ["Cookie name"];

The following figure shows the number of cookies that have been read:


Response. write (cookie. value. tostring (); master the above key points, it is very easy to read the cookie, the following is the program code to read the cookie (read. aspx): <% @ Language = "C #" %>
<SCRIPT runat = "server">
Void readclicked (Object sender, eventargs E)
{
// Obtain the cookie name entered by the user
String strcookiename = namefield. text;
// Obtain the cookie
Httpcookie cookie = request. Cookies [strcookiename];
// Determine whether the cookie entered by the user exists
If (null = cookie ){
Response. Write ("no specified Cookie found <br> <HR> ");
}
Else {
// Find the specified cookie and display the cookie value
String strcookievalue = cookie. value. tostring ();
Response. Write (strcookiename + "cookie value: <B>"
+ Strcookievalue + "</B> <br> <HR> ");
}
}
</SCRIPT>
<HTML>
<Body>
Read the specified cookie value on the C # page. <br>
<Form runat = "server">
Enter the cookie name to read: <asp: textbox id = "namefield" runat = "server"/>
<Asp: button text = "read cookie" onclick = "readclicked" runat = "server"/>
</Form>
</Body>
</Html>

Is the interface after the code is run:


Figure 02: program running interface for reading the value of a specified cookie

Iv. Summary:

So far, we have introduced most of the content for Cookie programming using C. In fact, cookies play a major role in the Internet. For example, it allows a Web site to track the access times of a specific visitor, the last access time, and the path of the visitor to the site. It can also tell online advertisers the number of clicks on an advertisement, in this way, users can more accurately deliver advertisements. It allows users to access some websites they have browsed without entering their passwords and usernames; the most important thing is that it can help the site collect user data for personalized services. After mastering C #'s cookie programming, you can make full use of cookies in the program to implement these functions. Do not believe it.

Related Article

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.