Cookie programming knowledge in ASP.NET

zhaozj2021-02-16  85

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 you start discussing 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 the number of cookies that your site can be 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 cookie

You can use the page's response (English) attribute to write cookies, which allows users to add information to information presented by pages to the browser. 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 cookies, 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 that 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

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

Response.cookies.add (acookie)

This example adds two cookies to the cookies collection, one called "username" and the other 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 Site cookies in the file name format for @ .txt file, where 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 it will be saved 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 of the directory by modifying 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 (sub-key) 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 a 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 write the same cookie, each cookie with two sub-keys: Response.Cookies ("Userinfo") = "Mike" response.cookies ("userinfo") ("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.EXPIRES = DATETIME.NOW.ADDAYS (1) Response.cookies.add (ACOOKIE) Control cookie valid range By default, all cookies of a site Saved together 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 cookies of the site. But sometimes you may want cookies to be more targeted, then you can set the valid range of cookies by two ways: Limit the valid range of the cookie to a folder on the server, actually limit the cookie restriction 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.

Limiting 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 direct settings 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 valid 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 cookie's Domain property, as shown below: Response.cookies ("domain"). Value = datetime.now.tostring response.cookies ("domain"). Expires = datetime.now.addays (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" This cookie can be used in the primary domain, sales.contoso.com.

Reading cookies When the browser sends a request to the server, the server's cookie will send it together 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 to get the value of cookie named "username" and display the value in the Label control: if Not Request.Cookies ("UserName") is nothing the 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) Endiff should make sure that the cookie does exist before getting the value of the cookie. 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 for obtaining a sub-key value: if NOT Request.Cookies ("UserInfo") is nothing kil1.text = _ server.htmlencode (Request.Cookies ("Userinfo") ("UserName") Label2.Text = _ Server.htmlencode ("UserInfo") ("UserInfo")) Endiff In the example above, I get the value of the subkey "lastvist", in the previous discussion, I set this value set A string representation for a DateTime value.

Keep in mind that cookies saves the value in the form of a string, so you must use the lastvisit value as a date, you must convert it: DIM DT AS DATETIME DT = CDATE ("UserInfo") ("Lastvisi" ")) The type of cookie neutrons is the collection of NameValueCollection (English) type. Therefore, another method for acquiring a single subkey is to get a set of subkey, and then extract the value of the subkey according to the name of the name, as follows: if NOT Request.Cookies ("UserInfo" is nothing the dim userinfocookiecollection as _ system. Collections.Specialized.NameValueCollection UserInfoCookieCollection = Request.Cookies ( "userInfo"). Values ​​Label1.Text = Server.HtmlEncode (UserInfoCookieCollection ( "userName")) Label2.Text = Server.HtmlEncode (UserInfoCookieCollection ( "lastVisit")) End If you 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 example of the Cookie collection, assuming 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 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 (Acoo.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" is, ASP.NET use this to save the Cookie The unique identifier for your session. 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 you detect a sub-key, get sub-keys 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 & = "subkey name =" & subkeyname "
"output & =" sub-key = "& subkeyValue &"

"Next Else output & =" value = "& Server.HtmlEncode (aCookie.Value) &"

"End If Next Label1.Text = output you can also be extracted as the sub-key NameValueCollection objects as follows: 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.h Tmlencode (cookievaluenames (j)) SubkeyValue = Server.htmlencode (cookievalues ​​(j)) Output & = "sub-key name =" & SubkeyName & "
" Output & = "=" & SubkeyValue & "

"Next Else output & =" value = "& aCookie.Value &"

"End If Note: Remember, the reason I call Server.HtmlEncode method, just because I want the page Display the value of the cookie.

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, 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, you don't actually change the cookies directly. 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 cookie for storing site access: Dim Counter As Integer if Request.cookies ("counter") is nothing kil = 0 else counter = cint (Request.Cookies ("counter"). Value) Endiffies = 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 cookies Delete cookies (i.e., 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 Cookie: Dim i as integer as integer = request.cookies.count - 1 for i = 0 To Limit Acookie = Request.Cookies (i) ACOOKIE.EXPIRES = DATETIME.NOW.EXPIRES = DATIME.NOW.ADDAYS (-1) Response.cookies.add (acookie) Next Modify or delete the subkey Method for modifying a single subkey is the same as the method originally created: Response. Cookies ("UserInfo") = datetime.now.tostring response.cookies ("userinfo"). Expires = datetime.now.adddays (1) More complex issues is 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 you use cookies, you have to 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 the browser accepts cookie I have mentioned a potential problem in the previous cookie restriction, that is, the user can set up your 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.

(Maybe you need to know, but httpbrowsercapabilities.cookies property [English] property does not tell you whether cookies are enabled, but can only tell if the current browser supports cookie.) A method for determining whether the browser accepts cookie Write a cookie first, then try 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 dam, "AcceptsCookies") Is Nothing The 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 the 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 'accept cookies? If Request.Cookies ( "TestCookie") Is Nothing Then 'no Cookie, there is no 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 =" & acceptscookies, _ true) End Sub After reading the Redirect query string variable, the code is trying 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 until 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.

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

New Post(0)