Asp. NET using cookies to keep the client information

Source: Internet
Author: User
Tags datetime range tostring
asp.net|cookie|cookies| Client The things I eat now are fixed to food, so it's not surprising that the theme for this week is cookies.



Cookies are used to store specific user information, which provides a useful way in web programs. For years, JavaScript developers have done a lot of work on cookies. Similarly, ASP. NET also provides access to cookies through the system.web space name. Although you should not use cookies to store sensitive data, they are an excellent choice for handling lock-fine data, such as color parameter selections or last-accessed dates.

Pass Cookies
A cookie is a small file stored on the client computer. If you are a Windows user, you can view the cookie path in the user path, which is the documents and settings path. This path contains a text file with the name of the file:

Username @ Web site domain that created the cookie

(User name @ Create a cookie site domain name)

The. NET system.web space name contains three classes that you can use to process client cookies:

HttpCookie: Provides a way to establish and manipulate the security type of independent HTTP cookies.

The Httpresponse:cookies property allows client cookies to be manipulated.

The Httprequest:cookies property allows access to client-operated cookies.

The Cookies property of the HttpResponse and HttpRequest objects will return a HttpCookieCollection object that contains the addition of a separate cookie to the collection (collection) and from the collection ( Collection) to obtain a separate cookie.

HttpCookie class
HttpCookie A separate cookie that is set up for use in customer storage. Once the HttpCookie object is created, you can add it to the cookie property of the HttpResponse object. Similarly, you can access existing cookies through the HttpRequest object. The HttpCookie class contains the following public properties:

Domain name: Gets or sets the domain name associated with a cookie that can be used to restrict cookie access in a specific area.

Expires (term): Gets or sets the expiration date and time of the cookie, and you can set it to a past date to automatically terminate or delete the cookie.

Names (name): Gets or sets the cookie name.

Path (PATH): Gets or sets the virtual path of the cookie. This property allows you to limit the range of cookies, that is, access cookies can only be restricted to a specific folder or path. Setting this property restricts access to only a specific path and all files under that path.

Secure (Secure): Sends a signal to indicate whether secure Sockets Layer (SSL) is used to send a cookie value.

Value: Gets or sets a separate cookie value.

Values (information): Returns a collection of key/value contained in a cookie.

Although these are not yet the most exhaustive list, it provides the things that are needed to handle cookies. For the use of these attributes, the following vb.net examples give the best understanding:

Dim TestCookie as New HttpCookie ("lastvisited")

Testcookie.value = DateTime.Now.ToString

Testcookie.expires = DateTime.Now.AddDays (7)

Testcookie.domain = "Builder.com"

RESPONSE.COOKIES.ADD (TestCookie)

This code snippet establishes a new cookie named lastvisited and assigns the current date and time value. Similarly, the cookie expiration period is set to one weeks and the relevant range is populated. Once an object is established, the object can be added to the client's cookie collection by the Add method of the Response.Cookies object. There are two methods in the HttpCookie constructor:

HttpCookie objectname = New HttpCookie ("CookieName")

HttpCookie objectname = New HttpCookie ("CookieName", "Cookievalue")

Similarly, the Response object contains a Setcookie method that can accept a HttpCookie object.
Once cookies are stored on the client, there are many different ways to provide you access to them. If you know the cookie name, you can use the HttpResponse object to easily access its value. The following vb.net line shows the value associated with the cookie:





Response.Write (Request.Cookies ("lastvisitied"). Value)



In addition, a complete list of cookies can be accessed through a HttpCookieCollection object. This allows the cookie list to be accessed using a for loop. The following C # code illustrates such an example:

HttpCookieCollection cookies;

HttpCookie Onecookie;

cookies = Request.Cookies;

string[] Cookiearray = cookies. AllKeys;

for (int i=0; I < Cookiearray.length; i++) {

Onecookie = Cookies[cookiearray[i]];

Response.Write (Onecookie.name + "-" + onecookie.value);

}



Vb. NET, the corresponding code is as follows:



Dim I as Integer

Dim Onecookie as HttpCookie

For i = 0 to Request.cookies.count-1

Onecookie = Request.Cookies (i)

Response.Write (Onecookie.name + "-" + onecookie.value)

Next I

Stability is also a point of view
Cookie files are stored on the client machine, so your users can delete or change them arbitrarily. In addition, users can also make cookies invalid. For this reason, keep in mind that you do not rely on cookie data. You should keep important information in the server--especially in a database.

Storing critical information in a cookie is considered a low-level program because it is easily compromised because the information is located in a file on the client machine. At this point, one approach is to use SSL, which is a better way to avoid sensitive information.



Can I use cookies?
Users can invalidate cookie support on their own browsers. You can access these settings in your own code to decide whether to support cookies. The request object satisfies this idea, and the following vb.net code shows the process:



If Request.Browser.Cookies = True Then

' Use cookies

Else

' No cookie Support

End If



You can combine code to use cookie values. The following C # Snippet tests the cookie support and displays the results in a text box accordingly:

if (Request.Browser.Cookies = = True)

{

if (request.cookies["LastVisited1"] = = null)

{

HttpCookie Newcookie = new HttpCookie ("LastVisited1", DateTime.Now.ToString ());

Newcookie.expires = DateTime.Now.AddYears (1);

RESPONSE.COOKIES.ADD (Newcookie);

This.txtName.Text = "Is this your";

} else {

This.txtName.Text = "We haven ' t seen you since" +

request.cookies["LastVisited1"]. Value;

} }



You can add this code snippet to the Page_Load event in the ASP.net page.



Another way to save your data
Asp. NET provides a variety of ways to save specific user data. One of the old methods is cookies. For sensitive data, although cookies are not the best method, it is the best choice for affinity options (benign items) such as color parameter selection, last access date, and so on. While these sensitive data are important, it is not the end of the world that data is lost when a user's computer crashes.


--------------------------------------------------------------------------------


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.