Basic knowledge of cookie programming in ASP.NET

xiaoxiao2021-03-06  122

Introduction Cookies provides a useful way for web applications to save user-related information. For example, when a user accesses your site, you can use cookies to save user preferences or other information, so that when users access your site next time, the application can retrieve the previously saved information. This article describes the application of cookies in the ASP.NET application to display the technical details of cookies in ASP.NET, such as writing cookies, and then read them. At the same time, you will also introduce you to the various features and special circumstances of cookies, as well as the support of cookies. What is cookie? Cookie is a small text message, accompanied by user requests and pages pass between web servers and browsers. Each time the user has access to the site, the web application can read the information contained in the cookie. Assuming that your application is sent to the user not just a page, there is a cookie that contains the date and time when the user requests access to a page on your website www.contoso.com. The user's browser also got this cookie while getting this cookie and saved it in a folder on the user's hard disk. Failure, if the user accesses the page on your site again, the browser will find the cookie associated with the URL on the local hard disk when the user enters the URL www.contoso.com. If the cookie exists, the browser sends it to your site along with the page request, and your application can determine the date and time of the user's last access site. You can send a message to the user based on this information, or you can check the expiration time or perform other useful features. Cookie is associated with a Web site instead of a specific page, so regardless of the user requesting to browse which page in the site, the browser and server will exchange the cookie information of www.contoso.com. When the user accesses other sites, each site may send a cookie to the user browser, and the browser saves all of these cookies separately. The above is the basic working principle of cookie. So what uses for cookies? The most fundamental use is that cookies can help the Web site to save information about visitors. More generally, cookie is a method of maintaining a continuity of web applications (ie, "Status Management"). The browser and web server are always disconnected outside the short actual information exchange phase, while the user sends to the web server is individually processed separately, independent of all other requests. However, in most cases, it is necessary to let the web server identify you when you request a page. For example, a web server on a shopping site tracks each shopper so that the site can manage shopping carts and other user-related information. Therefore, the role of cookie is similar to business card, which provides relevant identification information that helps applications determine how to continue. All of these purposes can be used to remember you in order to remember your Web site. For example, a site that implements public opinion can simply use cookies as a Boolean value, indicating whether your browser has participated in voting, thereby avoiding you repeatedly voting; and those who require users to log in can be used to determine if you have Log in, so you don't have to enter credentials each time.

For more background information about cookies, it is recommended that you read the "How Internet Cookies Work" in the Verizon Web site, address http://www22.verizon.com/about/community/learningcenter/articles/displayArticle1/0,4065, 1022Z1,00.html (English). The author explained in detail what cookie and how cookie exchange information between browser and servers, and he has also fully summarized the privacy issues involved in cookies. By the way, do you want to know why they are called "cookie"? Jargon File (also known as "The New Hacker's Dictionary") version 4.3.3 gives an accurate definition and reasonable explanation of the word source of this term. You can find related items at http://www.catb.org/~esr/jargon/jargon.html#cookie (English). In this subsequent content, this article will assume that you already know what is cookie, and assumes that you have clear why you want to use cookies in the ASP.NET application. Cookie's restrictions before starting to discuss the technical details of cookie, I would like to introduce several restrictions on cookie applications. Most browsers support up to 4096 cookies. If you want to save several values ​​to the user's computer, this space is already large enough, but you can't save the data set or other large number of cookies. data. In practical applications, you may not want to save a large number of user information in cookies, and only want to save user numbers or other identifiers. After that, when the user accesses your site again, you can use the user ID to find the details of the user in the database. (For instructions for saving user information, see cookie and security.) The browser also limits your site to save the number of cookies saved on the user's computer. Most browsers only allow each site to save 20 cookies. If you try to save more cookies, the most saved cookies will be deleted. Some browsers will restrict the total number of cookies from all sites, which is usually 300. The cookie restrictions you most encountered are: Users can set their own browsers and refuse to accept cookies. You can't help solve this problem unless you don't use cookies but through other mechanisms to save user-related information. A common way to save user information is a session state, but the session state rely on cookies. This is elaborated in the back cookie and session state. Note: For more information on the options for saving information in status management and web applications, see Introduction to Web Forms State (English) and State Management Recommendations. More general experience is probably, although cookies is very useful in applications, applications should not depend on capant cookies. With cookies, you can make a brocade, but don't use them to support key features. If your application must use cookies, you can determine if the browser accepts cookies. I have given a test method for checking the browser after checking the browser in this article.

Write cookies You can use the page's response (English) attribute to write cookies, which allows users to add information to information presented by the page. The Response object supports a collection called cookies (English), you can add cookies to which you want to write to your browser. Note: The response objects and request objects to be discussed below are the properties of the page containing the HTTPRESPONSE (English) and HttpRequest (English) class instance. To find information about Response and Request in your document, see the contents under HttpResponse and HttpRequest. When you create a cookie, you need to specify several values. Initially, you want to specify the name of the cookie and the value saved therein. You can create multiple cookies, each cookie must have a unique name so that you can identify when you read. (Cookie is saved by name, so if you have created two names of the same cookie, the one saved later will overwrite the previous one.) You may also want to specify the expiration date and time of the cookie. Cookie is generally written to the user's disk, and then may always stay on the disk. Therefore, you can specify the date and time of the cookie expired. When the user accesses your site again, the browser will check the cookie collection of your site. If a cookie has expired, the browser does not send this cookie to the server with the page request, but deletes this expired cookie. . (Your site may have written multiple cookies on the user's computer, each cookie has its own expiration date and time.) Please note that the browser is responsible for managing the cookie on the hard disk, which will affect your application In the use of cookies, I will introduce this aspect. How long is a cookie effective? This depends on the use of cookie, in other words, how long it depends on your application needs a cookie value to maintain a valid time. If you use the visitor of the cookie statistics website, you can set the validity period to 1 year. If a user has not accessed your site for a year, you can use the user as a new visitor; if you use cookie to save your user The preferences, you can set it to be valid forever (for example, 50 years later), because regular resetting preferences are troublesome. Sometimes you may need to write a cookie that is expired within a few seconds or minutes. In this article, check whether the browser accepts the cookie section, I list one example, and the actual validity period of the cookie created in this example is only a few seconds. Note: Don't forget that users can delete cookies on their own computer, so even if you save long-term valid cookies, users can decide to delete them all, and clear all settings saved in cookies. If you do not set the validity period of the cookie, you can also create a cookie, but it does not save to the user's hard drive, but it will become part of the user session information. This cookie will be deleted if the user closes the browser or session timeout. This non-permanent cookie is very suitable for saving only information saved in a short time, or saving information about the customer's computer disk due to security reasons.

For example, if the user uses a public computer, you don't want to write cookies to the disk of this computer, you can use non-permanent cookies. You can add cookies to the Response.cookies collection through a variety of ways. The following example introduces two methods to complete this task: Response.Cookies ("UserName"). Value = "Mike" response.cookies ("username"). Expires = datetime.now.adddays (1) DIM ACOOKIE AS New httpcookie ("Lastvisit") ACOOKIE.VALUE = datetime.now.tostring acoo.expires = datetime.now.adddays (1) Response.cookies.add (ACOOKIE) This example adds two cookies to the cookies collection, one called " UserName, another is called "lastvisit". For the first cookie, I set the value of the Response.cookies collection. You can use this method to add a value to the collection because response.cookies are derived from the special collection of NameObjectCollectionBase (English) type. For the second cookie, I created an instance of the cookie object (HTTPCOOKIE [English] type) and set its properties, and then added it to the Response.Cookies collection via the Add method. When instantiate the HTTPCookie object, you must pass the cookie name as part of the constructor. These two examples have completed the same task, namely written to the browser. Which method you want to use is mainly depends on your personal preference. You may find that the second method is slightly easier in setting the cookie property, but you will notice that the differences in the two are not very big. In both methods, the validity value must be a DateTime type. The "LastVisited" value is also a date / time value. But in this case, I must convert the date / time value to a string because any value in cookie is ultimately saved in the form of a string. View your cookie You may find that you can help you very helpful for creating a cookie. And checking cookies is relatively easy, because they are text files, the key is that you can find them. Different browser saves cookies. I will introduce Internet Explorer how to save cookies. If you are using other browsers, check the help of the browser to learn about the knowledge of cookie processing. A simple way to see cookie is to let Internet Explorer look for you. In Internet Explorer, select Internet Options from the Tools menu, click Settings in the General tab, and then click View File. Internet Explorer will open a window that displays all temporary files, including cookies. Find files starting with "cookie:" in the window or lookup text files. Double-click a cookie to open it in the default text file. You can also find the Cookie text file on your hard drive to open cookies.

Internet Explorer saves the cookies of the site in the file name format @

In the file of .txt,

It is your account name. For example, if your name is MikePope, the site you have access is www.contoso.com, then the cookie of the site will be saved in a file called MikePope@www.contoso.txt. (This file name may contain a sequential number, such as MikePope@www.contoso [1] .txt.)

This cookie text file is related to the user, so save it separately according to the account. For example, in Windows XP, you can find a cookie file in the directory shown below:

C: / Documents and Settings /

/ Cookies

To find the latest created cookies, you can sort the contents according to the modification date and find the recently modified file.

You can open cookies using the text editor. If the file contains multiple cookies, these cookies will be separated by an asterisk (*). The first line of each cookie is the name of the cookie. The second line is a value, and the remaining rows contain the daily processing information of the cookie, such as expiration date and time. There is also a simple check in cookie. If you change the length of the cookie name or value, the browser will modify and remove the cookie.

Multi-value cookie (subkey)

The above example uses a cookie for each value (username, last access time) to be saved. You can also save multiple names / value pairs in a cookie. Name / value is also called "key" or "subkey", depending on the content you read. (If you are familiar with the structure of the URL, you will find that the sub-key is very similar to the query string.) For example, if you don't want to create two separate cookies named "UserName" and "Lastvisit", you can create a name. Cookies for "UserInfo" and make them two sub-keys: "UserName" and "Lastvisit".

There are many reasons that let us use the sub-keys instead of separate cookies. It is most important to put the associated or similar information in a cookie. In addition, since all information is in a cookie, the cookie attributes such as the validity period apply to all information. (Of course, if you want to specify different expiration date for different types of information, you should save the information in separate cookies.)

Cookies with sub-keys can also help you reduce the size of the cookie. As mentioned earlier, the total size of the cookie is limited to 4096 bytes, and cannot save more than 20 cookies for a website. With a single cookie of the belt key, the number of Site cookies will not exceed 20 restrictions. In addition, a cookie will occupy a basic space overhead of approximately 50 characters (for saving validity period information, etc.), plus the length of the value saved, and its sum is close to 4K. If you use five sub-keys instead of five separate cookies, you can save the basic space overhead of the four cookies, saving a total of about 200 bytes.

To create a cookie with a sub-key, you can use a variety of syntax used to write a single cookie. The following example shows two different ways to prepare the same cookie, each of which has two sub-keys:

Response.cookies ("Userinfo") = "Mike" Response.Cookies ("lastvisit") = datetime.now.tostring

Response.cookies ("UserInfo"). Expires = DateTime.now.adddays (1)

DIM ACOOKIE AS New Httpcookie ("UserInfo")

Acookie.values ​​("UserName") = "Mike"

ACOOKIE.VALUES ("Lastvisit") = datetime.now.tostring

Acookie.expires = datetime.now.adddays (1)

Response.cookies.add (acookie)

Control cookie effective range

By default, all cookies of a site are saved on the client, and all of these cookies will send them to the server with the request sent to the site, that is, each page of the site can get all the sites. Cookie. But sometimes you may want cookies more targeted, then you can set the valid range of cookies by two ways:

Limit the valid range of the cookie in a folder on the server, actually limiting the cookie to an application on the site.

Set the valid range to a domain, allowing you to specify which subdomains in the domain can access cookies.

Limit cookies to a folder or application

To limit the cookie to a folder on the server, set the cookie's Path property as follows:

DIM AppCookie as new httpcookie ("AppCookie")

AppCookie.Value = "Written" & now.toString

AppCookie.expires = now.adddays (1)

AppCookie.path = "/ Application1"

Response.cookies.add (appcookie)

Of course, you can also write cookies by setting RESPONSE.COOKIES, as described above.

The path can be a physical path in the site root directory, or a virtual root directory. In this way, cookies can only be used for pages in the Application1 folder or virtual root directory. For example, if your site is named www.contoso.com, the cookies generated in the previous example can only be used for pages with http://www.contoso.com/application1/ and all pages under this folder. Not applicable to pages in other applications, such as http://www.contoso.com/application2/ or http://www.contoso.com/ below.

Tip: By testing the Internet Explorer and Mozilla browsers, the path used here is case sensitive. In general, the URL on the Windows server is not case sensitive, but this case exception. You cannot control how users enter URLs in the browser, but if your application depends on cookies related to a specific path, make sure that the URL in all hyperlinks you created is matched to the case of the PATH property value. . Limit the effective range of cookies to the domain

By default, cookies are associated with a particular domain. For example, if your site is www.contoso.com, the cookie you have written is sent to the server when the user requests the page to the site. (There is a cookie with a specific path value, except for the previous section, I just explained.) If your site has a subdomain (such as contoso.com, you can use the cookie The specific subdomain is associated. To do this, you need to set the Domain property of the cookie, as shown below:

Response.cookies ("domain"). Value = datetime.now.toString

Response.cookies ("Domain"). Expires = DateTime.now.adddays (1)

Response.cookies ("domain"). Domain = "support.contoso.com"

If you set the domain in this way, cookies can only be used to specify the page in the subdomain.

You can also use the Domain property to create cookies that can be shared in multiple subdomains. For example, the domain is set as follows:

Response.cookies ("domain"). Value = datetime.now.toString

Response.cookies ("Domain"). Expires = DateTime.now.adddays (1)

Response.cookies ("domain"). Domain = "contoso.com"

This way, this cookie can be used in the main domain, sales.contoso.com and support.contoso.com.

Read cookie

When the browser sends a request to the server, the server's cookie will send it with the request. In the ASP.NET application, you can use the Request object to read the cookie. The structure of the REQUEST object is basically the same as the structure of the Response object, so the method read from the Request object is very similar to the method of writing cookies in the Response object. The following example shows two ways, the purpose is to get the value of the cookie named "username" and display the value in the Label control:

IF Not Request.cookies ("Username") is nothing then

Label1.text = Server.htmlencode (Request.Cookies ("UserName"). Value)

END IF

IF Not Request.cookies ("Username") is nothing then

DIM ACOOKIE AS HTTPCOOKIE = Request.Cookies ("Username") label1.text = server.htmlencode (acookie.value)

END IF

Before getting the value of the cookie, you should make sure that the cookie does exist. Otherwise, you will get a System.NullReferenceException (English) exception. It is also important to note that before the content of the cookie is displayed, I call the HTTPServerutility.htmlencode method to encode the contents of the cookie. This is done because I want to display the content of cookie (usually you don't do this) and make sure there is no malicious user adds an executable script to the cookie. For more information on cookie security, see cookie and security.

Note: Different browsers on different browsers are also different, so different browsers on the same computer do not necessarily read each other cookies. For example, if you use Internet Explorer to test a page, then use another browser to test, then the latter will not find the cookie saved by Internet Explorer. Of course, most people generally use the same browser for web interaction, so there is no problem in most cases. But sometimes you will have problems, such as testing applications to compatibility with your browser.

The method of reading the cookie neutron key value is similar to the method of setting this value. The following is a method of obtaining a sub-key value:

IF not Request.cookies ("UserInfo") Is Nothing Then

Label1.text = _

Server.htmlencode (Request.Cookies ("Userinfo") ("UserName"))

Label2.text = _

Server.htmlencode (Request.Cookies ("lastvisit")))

END IF

In the above example, I get the value of the sub-key "lastvist", in the previous discussion, I set this value to a string representation of the DateTime value. Keep in mind that cookies saves the value in the form of a string, so you must convert the lastvisit value as a date, you must convert it:

DIM DT AS dateTime

Dt = cdate (Request.Cookies ("lastvisit")

The type of cookie neutron key is a collection of NameValueCollection (English) type. Therefore, another method of acquiring a single subkey is to get a collection of subkey, then press the value of the subkey, as shown below:

IF not Request.cookies ("UserInfo") Is Nothing Then

DIM UserInfocookieCollection As _

System.collections.Specialized.NameValueCollection

UserInfocookieCollection = Request.Cookies ("UserInfo"). VALUES

Label1.text = Server.htmlencode ("UserName")) Label2.text = Server.htmlencode ("Lastvisit")

END IF

Just like setting cookie, which way to use Cookies is also determined by yourself.

What is the validity period?

You can read the name and value of the cookie, in addition to this, the information about cookie needs to be understood is not a lot. Although you can get the Domain and Path properties, the use of these properties is limited. For example, you can read the Domain property, but if your page is not in the same domain, you will not receive the cookie at the location of the page.

You can't read the Expiration date and time of the cookie. In fact, when the browser sends a cookie information to the server, the browser has not included the expiration information. You can read the Expires property, but always return to zero date / time values.

In the previous Writing Cookie section, I have already said that the browser is responsible for managing cookies, and the Expires property is very well confirmed. The main role of the Expires property is to help the browser perform daily management about cookies. From the perspective of the server, the cookie either does not exist, so the validity period is not useful for the server. So, the browser does not provide this information when sending cookies. If you need a cookie's expiration date, you must be reset, about this, I will introduce and delete cookies.

More specifically, you can read the expires properties that have been set in the Response object before sending a cookie to the browser, but you cannot get validity period information from the returned REQUEST object.

Read the cookie collection

The previous example assumes that you want to read the name known cookie. Sometimes you may need to read all cookies available for the page. To read all the cookies of all cookies available for the page, you can use the following code to traverse the Request.Cookies collection:

DIM I as integer

Dim Output as string = "" "

DIM ACOOKIE AS HTTPCOOKIE

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

Acookie = Request.cookies (i)

Output & = "Cookie Name =" & Server.htmlencode (Acookie.Name) & "

"

Output & = "Cookie Value =" & Server.htmlencode (ACOOKIE.VALUE) & _

"

"

NEXT

Label1.text = OUTPUT

Note: When you run this code, you are likely to see a cookie named "ASP.NET_SESSIONID", ASP.NET with this cookie to save your session's unique identifier. This session cookie will not be saved to your hard drive permanently. For more information on session cookies, see the cookie and session status later in this article.

The previous example has a limit: if the cookie has a subkey, the sub-key is displayed in a separate name / value string. Cookie's Haskeys (English) property can tell you if the cookie has a subkey. If there is a child button, you can drill down down in the subkey set, get the names and values ​​of each subkey. As mentioned earlier, you can get information about sub-keys from the cookie property values ​​(English), which is a collection of type names NameValueCollection. You can read the child key value from the VALUES collection according to the index value. The corresponding sub-key value can be obtained from the member AllKeys (English) of the VALUES collection, which will return a string collection.

The following example is a modification of the previous example. In the example, use the Haskeys property to test the subkey. If the sub-key is detected, get the subkey from the VALUES collection:

DIM I as integer

DIM J AS INTEGER

Dim Output as string = "" "

DIM ACOOKIE AS HTTPCOOKIE

Dim SubkeyName As String

DIM SubkeyValue As String

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

Acookie = Request.cookies (i)

Output & = "Name =" & acookie.name "

"

IF ACOOKIE.HASKEYS THEN

For j = 0 to acookie.values.count - 1

SubkeyName = Server.htmlencode (Acookie.values.allKeys (j))

SubkeyValue = Server.htmlencode (acookie.values ​​(j))

Output & = "Sub Key Name =" & SubkeyName & "

"

Output & = "Sub Keys =" & SubkeyValue & "

"

NEXT

Else

Output & = "value =" & Server.htmlencode (ACOOKIE.VALUE) & "

"

END IF

NEXT

Label1.text = OUTPUT

You can also extract the sub-keys as the NameValueCollection object, as shown below:

IF ACOOKIE.HASKEYS THEN

DIM CookieValues ​​As _

System.collections.Specialized.NameValueCollection = ACOOKIE.VALUES

Dim cookievaluenames () as string = cookievalues.allkeys

For j = 0 to cookievalues.count - 1

SubkeyName = Server.htmlencode (cookievaluenames (j))

SubkeyValue = Server.htmlencode (cookievalues ​​(j))

Output & = "Sub Key Name =" & SubkeyName & "

"

Output & = "Sub-key =" & SubkeyValue & ""

NEXT

Else

Output & = "Value =" & Acoo.Value & "

"

END IF

Note: Keep in mind, calling the Server.htmlencode method, just because I want to display the value of the cookie on the page. If you only test the value of the cookie, you don't have to encode it before use.

Modify and delete cookies

Sometimes you may need to modify a cookie to change its value or extend its validity. (Remember, because the browser does not pass the validity period information to the server, you can't read the cookie's expiration date.)

Of course, don't actually change the cookie. Although you can get cookies from the Request.Cookies collection and do it, cookie itself still exists in a place on the user's hard drive. Therefore, modifying a cookie actually creates a new cookie with a new value, and sends the cookie to the browser to overwrite the old cookies on the client.

The following example illustrates how to change the value of cookies used to store the number of access times:

DIM Counter as integer

IF Request.Cookies ("counter") is nothing then

COUNTER = 0

Else

Counter = CINT (Request.Cookies ("counter"). Value)

END IF

Counter = 1

Response.cookies ("counter"). Value = Counter.toString

Response.cookies ("counter"). Expires = datetime.now.adddays (1)

or:

Dim Ctrcookie as httpcookie

DIM Counter as integer

IF Request.Cookies ("counter") is nothing then

Ctrcookie = new httpcookie ("counter")

Else

Ctrcookie = Request.Cookies ("counter")

END IF

Counter = cint (ctrcookie.value) 1

Ctrcookie.value = counter.tostring

Ctrcookie.expires = datetime.now.adddays (1)

Response.cookies.add (ctrcookie)

Delete cookie

Delete cookies (that is, physical deletion of the cookie from the user's hard disk) is a form of modifying the cookie. Since cookies is located in a user's computer, you can't delete it directly. However, you can let your browser delete cookies for you. Modifying a cookie method The following has been described in front (that is, create a new cookie with the same name), and the difference is to set it to the past date. When the browser checks the validity of the cookie, this expired cookie will be removed.

Therefore, the method of deleting cookies is the same as creating the cookie, but only sets its validity period to a date. The following example is more interesting than deleting a single cookie, which uses the method to delete all cookies of the current domain: DIM I as integer

Dim cookiename as string

DIM LIMIT AS INTEGER = Request.cookies.count - 1

For i = 0 to limit

Acookie = Request.cookies (i)

Acookie.expires = datetime.now.adddays (-1)

Response.cookies.add (acookie)

NEXT

Modify or delete sub-keys

Modifying a single child key is the same as the method originally created:

Response.cookies ("UserInfo") ("lastvisit") = datetime.now.tostring

Response.cookies ("UserInfo"). Expires = DateTime.now.adddays (1)

More complex issues are how to delete a single subkey. You can't just reset the Cookie's expiration date, because this can only delete the entire cookie without deleting a single subkey. The actual solution is to operate on the VALUES collection of the cookie containing the subkey. First, recreate the cookie by getting a cookie from the Request.Cookies object. Then, you can call the REMOVE method of the VALUES collection, pass the subkey name to be deleted to the Remove method. Next, you can usually add the modified cookie to the Response.Cookies collection to send the modified cookie to the browser.

The following code shows how to delete the subkey. In the example, the name of the subkey to be deleted is specified in the variable.

Dim SubkeyName As String

SubkeyName = "Username"

DIM ACOOKIE AS HTTPCOOKIE = Request.Cookies ("UserInfo")

Acookie.values.Remove (SubkeyName)

Acookie.expires = datetime.now.adddays (1)

Response.cookies.add (acookie)

Cookie and security

When using cookies, you must realize its inherent security weaknesses. The security I have referred to is not a privacy problem, as I am in front What is cookie? As described in this, privacy is a greater extent, and these users are very concerned about how the information in cookies is used. The safety of cookie is similar to security issues from clients. For beginners, as far as applications, cookies are another form of user input, which is easily illegally acquired and utilized by others. Since cookies are saved on their own computer, the user can at least see the information you saved in cookies. If the user is willing, modify the cookie before the browser sends you cookies.

So, don't save confidential information in cookies - username, password, credit card number, etc. Do not save the content that should not be mastered by the user in cookies, or save content that may be controlled by other people who steal cookies.

Similarly, it is skeptical about any information obtained from cookies. Don't think that the data obtained is the information you originally envissed. Security measures employed by handling the cookie value should be the same as the security measures employed when the user typed in the WEB page. For example, before the value is displayed, I will perform HTML encoding in the contents of the cookie. This is a standard method that purges the information obtained from the user before displaying, and the processing of cookie is the same. Another problem that needs to be concerned is that cookies are transferred between browsers and servers in the form of plain text, anyone who can intercept Web communication can read cookies. You can set up the cookie's properties so that they can only be transmitted on connections using the security socket layer (SSL, also known as https: //). SSL does not prevent the cookie stored on the user's computer to be read or operated by others, but it prevents Cookie from being taken by others during transmission. This article does not discuss SSL, but you must be clear, you can transfer cookies. For more information on SSL, see Secure Sockets Layer: Protect Your E-Commerce Web Site with SSL and Digital Certificate (English).

In the face of these security issues, how can I safely use cookies? You can save some unimported data in cookies, such as user preferences or other information that does not have a significant impact on the application. If you do need to save some sensitive information (such as user ID) in cookies, you can encrypt this information. One feasible method is to create an authentication ticket using the ASP.NET FORMS Authentication utility, saved as a cookie. This article does not discuss issues related to encryption, however, if you need to save sensitive information in cookies, you should try to hide information to prevent being able to be used by others.

In Mitigating Cross-Site Scripting WITH HTTP-Only Cookies, you can learn more about cookies and security weaknesses.

Check if your browser accepts cookies

I have mentioned a potential problem in the previous cookie's restrictions, that is, the user can set up their own browser to refuse to accept the cookie. How can I know if you can read and write cookies? No errors occur when you cannot write cookies (for example, Response.cookies do not throw an exception) because the server does not track the presented page. The browser also does not send any information about its current cookie settings to the server. (Perhaps you need to know, but httpbrowsercapabilities.cookies property [English] property does not tell you if the cookie is enabled, but can only tell your current browser to support cookie.)

A method for determining whether the browser accepts cookie is to write a cookie before trying to read this cookie. If you can't read this cookie, you can think that the browser does not accept cookies.

I have written a simple example to explain how to test whether cookies are accepted. This example contains two pages. In the first page, I wrote a cookie and then reallied the browser to the second page. The second page attempts to read this cookie, turn the browser to the first page and add a query string variable with the test results to the URL.

The code of the first page is as follows:

SUB Page_Load () if not page.ispostback the

If Request.QueryString ("AcceptsCookies") Is Nothing Then

Response.cookies ("TestCookie"). Value = "OK"

Response.cookies ("TestCookie"). Expires = _

Datetime.now.addminutes (1)

Response.Redirect ("TestForCookies.aspx? Redirect =" & _

Server.urlencode (Request.URL.TOString))

Else

LabeLacceptscookies.text = "Accept cookie =" & _

Request.QueryString ("AcceptsCookies")

END IF

END IF

End Sub

The first page test has a reply. If not, search for query string variables containing test results. If the query string variable is not found, the test has not been completed, the code writes a cookie named "TestCookie". After writing cookies, sample calls response.redirect to switch to the test page (TestForCookies.aspx). The URL attached to the test page is a query string variable named Redirect, which contains the URL of the current page, so that the redirection can be redirected to the page after performing the test.

The test page can be composed entirely of code, and no controls are required. Here is the code I use:

SUB Page_Load ()

Dim Redirect As String = Request.QueryString ("Redirect")

DIM AcceptsCookies as string

'Do you accept cookie?

IF Request.Cookies ("TestCookie") Is Nothing Then

'No cookie, so you don't need to accept

Acceptscookies = 0

Else

Acceptscookies = 1

'Delete Test Cookie

Response.cookies ("TestCookie"). Expires = _

Datetime.now.adddays (-1)

END IF

Response.Redirect (Redirect & "? Acceptscookies =" & accessscookies, _

True)

End Sub

After reading the Redirect query string variable, the code attempts to read the cookie. In order to achieve daily management, if the cookie does exist, it will be deleted immediately. After the test is complete, the code is constructed from the URL passed from the Redirect query string variable. The new URL also includes a query string variable containing test results. The final step is to redirect the browser to the original page using the new URL.

This example is very simple, but illustrates the basic principles for testing by running the program and viewing results. Where the most important place to improve is to keep the cookie test results so that users do not have to repeat their tests every time you browse the original page. However, this does not actually do this. Cookie does not work, because it is obvious. Another possibility is to save the test results in a session state, but by default, the session status is also dependent on cookies, and if the browser does not accept cookie, the session status will not work. A solution to the latter problem is to use a cookie-free session state. The next section I will briefly introduce how the session status is collaborate with cookies. Cookie and session status

When the user accesses your site, the server creates a unique session for the user, and the session will continue to the end of user access. For each session, both ASP.NET maintain a server-based structure (session state), in which the application can save the user's related information. For more information, see Session State.

ASP.NET needs to track the session ID of each user, so that the user can map the user to the session status information on the server. By default, ASP.NET uses a non-permanent cookie to save the session state. If you use the example in the Read Cookie Collection of the Cookie section, you may find a session status cookie in the cookie.

However, if the user disables the cookie of the browser, the session status cannot use cookies to save the session ID, the session status will not work. That's why I checked whether the browser accepted in the cookie, I couldn't save the test results in the session state after the cookie test was completed, because there was no session state without cookies.

ASP.NET provides a solution that utilizes a cookie session. You can configure your own application, not saving the session ID in the cookie, but saved in the URL of the site page. The session ID is saved in the URL, that is, the ASP.NET saves the ID in the browser so that the ID can be retrieved when the user requests other pages.

There is no cookie session to avoid browsers to reject cookies, so that you can use session status. If your application depends on a session state, you may need to configure it so that it can use a cookie session. However, in some cases, if the user is shared with the URL - may be that the user sends URL to a colleague via email, and the user's session is still active - then the two users may share the same session, The results will be difficult to expect.

转载请注明原文地址:https://www.9cbs.com/read-126113.html

New Post(0)