Asp. Basic knowledge of cookie programming in net (6)

Source: Internet
Author: User
Tags date contains datetime session id tostring
asp.net|cookie| Programmatic deletion of cookies

Deleting a cookie (that is, physically removing the cookie from the user's hard disk) is a form of modifying the cookie. Because the Cookie is on the user's computer, you cannot delete it directly. However, you can have the browser delete cookies for you. The method of modifying a cookie has been described before (that is, a new cookie is created with the same name), and the difference is to set its validity period to a date in the past. When the browser checks the validity of a cookie, it deletes the expired cookie.

Therefore, the method of deleting a cookie is the same as the method for creating the cookie, except that it is set to a date in the past. The following example is slightly more interesting than deleting a single cookie by using a method that deletes all cookies in 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 a subkey

The method of modifying a single subkey is the same as the method that originally created it:

Response.Cookies ("UserInfo") ("lastvisit") = DateTime.Now.ToString
Response.Cookies ("UserInfo"). Expires = DateTime.Now.AddDays (1)

The more complex question is how to delete a single subkey. You cannot simply reset the expiration date of the cookie because it will only remove the entire cookie and not the individual subkeys. The real solution is to manipulate the Values collection of cookies that contain subkeys. First, recreate the cookie by getting a cookie from the Request.Cookies object. You can then call the Remove method of the Values collection, passing the name of the subkey that you want to delete to the Remove method. Next, you can usually add the modified cookie to the Response.Cookies collection to send the modified cookie back to the browser.

The following code shows how to delete a 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)

Cookies and security

When using cookies, you must be aware of their inherent security vulnerabilities. What I mean by security is not a privacy issue, as I am in front of what is a Cookie? , privacy is more of a problem for some users: these users are concerned about how the information in the Cookie is used. The security issue with cookies is similar to the security issue of obtaining data from the client. For beginners, cookies are another form of user input for applications, and are therefore susceptible to being illegally acquired and exploited by others. Because cookies are saved on the user's own computer, the user can at least see the information that you saved in the cookie. If the user wants to, you can also modify the cookie before the browser sends you a cookie.

Therefore, you should never keep confidential information in cookies-user name, password, credit card number, and so on. Do not store content that should not be available to the user in a cookie, nor save content that may be controlled by someone else who steals cookies.

Again, be skeptical about any information you get from cookies. Don't assume that the data you have is the information you originally conceived. The security measures used when handling Cookie values should be the same as those used to handle data typed by users in a Web page. For example, before displaying a value in a page, I would HTML-encode the contents of the Cookie. This is a standard method that can be used to purify information that is obtained from the user before it is displayed, and to treat cookies in the same way.

Another concern is that cookies are sent as plain text between browsers and servers, and anyone who can intercept WEB traffic can read cookies. You can set the properties of a Cookie so that it can only be transferred on a connection that uses Secure Sockets Layer (SSL, also known as https://). SSL does not prevent cookies that are stored on a user's computer from being read or manipulated by others, but it prevents cookies from being intercepted by others on the way to transmission. SSL is not discussed in this article, but you must be aware that you can protect the Cookie from transmission. For more information about SSL, see Secure Sockets layer:protect Your E-Commerce Web Site with SSL and Digital certificates (English).

How can you safely use cookies in the face of these security issues? You can save some unimportant data in a Cookie, such as user preferences or other information that has no significant impact on the application. If you do need to keep some sensitive information, such as a user ID, in a Cookie, encrypt the information. One possible approach is to use the ASP.net Forms authentication utility to create an authentication ticket that is saved as a Cookie. This article does not discuss encryption, but if you need to store sensitive information in cookies, you should try to take steps to hide the information from being embezzled by others.

In the article mitigating Cross-site scripting with http-only cookies, you can learn more about cookies and their security vulnerabilities.

Check to see if the browser accepts cookies

I mentioned a potential problem in the previous section on the limitations of cookies, where users can set their own browsers to refuse to accept cookies. How do I know if you can read and write cookies? No error occurs when a Cookie cannot be written (for example, Response.Cookies does not throw an exception) because the server does not track what happens after the page is rendered. The browser also does not send any information about its current Cookie settings to the server. (You may need to know, but the Httpbrowsercapabilities.cookies property does not tell you whether the cookie is enabled, and can only tell you whether the current browser supports cookies.) )

One way to determine whether a browser accepts cookies is to write a cookie before attempting to read the cookie. If you cannot read this cookie, you can assume that the browser does not accept cookies.

I've written a simple example to show how to test whether a Cookie is accepted. The example contains two pages. On the first page, I wrote a Cookie and redirected the browser to the second page. The second page tries to read the Cookie, redirects the browser to the first page, and adds a query string variable with the test result to the URL.

The code for the first page is as follows:
Sub Page_Load ()
If not Page.IsPostBack Then
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 tests whether there is a reply, and if not, searches for a query string variable (acceptscookies) that contains the results of the test. If the query string variable is not found, the test is not finished and the code writes a Cookie named "TestCookie". After writing out the Cookie, the example 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 that contains the URL of the current page, which can be redirected to the page after the test is executed.

The test page can consist entirely of code and does not need to contain controls. Here's the code I'm using:

Sub Page_Load ()
Dim Redirect as String = Request.QueryString ("redirect")
Dim AcceptsCookies as String
' Do you accept cookies?
If request.cookies ("TestCookie") is nothing Then
' No cookies, so 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 attempts to read the Cookie. In order to achieve day-to-day management, if the Cookie does exist, it is deleted immediately. After the test is complete, the code constructs a new URL from the URL passed by the redirect query string variable. The new URL also includes a query string variable that contains the test results. The final step is to redirect the browser to the original page using the new URL.

This example is very simple, but explains the basic principles of testing by running programs and viewing the results. One of the most needed improvements is to permanently save the Cookie test results so that users do not have to repeat the tests each time they browse the original page. However, this is not actually possible. Cookies do not work, because they are obvious. Another possibility is to save the test results in session state, but by default, session state also relies on cookies, and session state does not work if the browser does not accept cookies. The solution to the latter problem is to adopt a session state without cookies. In the next section, I'll briefly describe how session state works with cookies.

Cookies and Session state

When a user visits your site, the server creates a unique session for that user, and the session continues until the end of the user's access. For each session, ASP.net maintains a server-based structure (session state) in which the application can hold information about the user. For more information, see Session State (English).

ASP.net needs to be able to track the session ID of each user in order to map the user to session state information on the server. By default, ASP.net uses a non permanent Cookie to save session state. If you use the example in the "Read Cookie Collection" section of the Read cookie, you may find a session state cookie in the cookie.

However, if the user disables the browser's cookie, session state cannot use cookies to hold the session ID, and session state will not work. That's why I said in the previous check that the browser accepted the cookie that the test results could not actually be saved in session state after the cookie test, because there is no session state without cookies.

ASP.net provides a solution that utilizes a session without a Cookie. Instead of saving the session ID in a Cookie, you can configure your own application to save it in the URL of the site page. The session ID is saved in the URL, that is, ASP.net saves the ID in the browser so that the ID can be retrieved when the user requests another page.

A cookie-free session avoids the problem of a browser rejecting cookies, allowing you to use session state. If your application relies on session state, you may need to configure it so that it can use a Cookie-free session. However, in some cases, if a user shares a URL with someone else-perhaps by sending the URL to a coworker via e-mail and the user's session is still active-then eventually the two users may share the same session and the results will be unpredictable.


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.