Watch videos with subtitles in your language, upload your videos, create your own subtitles! Click here to learn more on "how to Dotsub"

Read, Write, and Delete Cookies in ASP.NET

0 (0 Likes / 0 Dislikes)
  • Embed Video

  • Embed normal player Copy to Clipboard
  • Embed a smaller player Copy to Clipboard
  • Advanced Embedding Options
  • Embed Video With Transcription

  • Embed with transcription beside video Copy to Clipboard
  • Embed with transcription below video Copy to Clipboard
  • Embed transcript

  • Embed transcript in:
    Copy to Clipboard
  • Invite a user to Dotsub
[Microsoft] [] [Chris Pels] Hi, my name is Chris Pels. In this video we're going to learn how to create and use cookies in an website. Get started by creating a website and, as many of you know, cookies are small pieces of text that you can associate with a website which are transferred down to the user's computer and stored on their hard disk when the user visits a page on the website. Cookies can be useful for storing small bits of information like identifiers for the user, last date and time the user visited the website, and other similar pieces of information. So what we're going to do is open up the code behind the default ASPX page and I will add a page load event, Then, in the page load event what we're going to do is demonstrate various ways that you can create and manipulate cookies on this website. Before we get started looking at how to create and use cookies we should understand some of the limitations of cookies. First is that they store a relatively small amount of information—up to 4096 bytes. Also, most browsers limit the number of cookies associated with a particular website and that is typically around 20 cookies, and then, overall, there's a limit that the browser imposes on the number of cookies across all sites, and that is about 300 cookies. So consider those factors when you start to plan how to use cookies in association with your website. The last thing about cookies is that all the data is stored as text so it's available for access on the user's computer, so you would not want to store any sensitive information in a cookie, Just information that helps identify a particular user, last visit to the site, and other non-critical information in case the user views the cookie while it resides in their website. There is a way to send the cookie information down to the browser and back up to the server in a secure fashion, but even though it's secure during the transmission process the cookie is still stored as plain text when it resides down on the user's hard disk. Now the fist thing we'll look at is how to write information to cookies and then have the cookies sent down to the user's browser and hard disk, and all the cookies are stored in a cookies collection, which is in the Response object. Here on the page, if we enter or use the Response object, we'll see there's a cookies collection and then there are 2 ways that we can add a cookie to the cookies collection. One is to just explicitly declare the name of the cookie. For example, let's say this cookie is going to store the date/time of the last visit, so we'll call the cookie LastVisit and then one of the properties of the cookie is value, and we'll assign to the value property the current date/time. We'll say Value=DateTime.Now and we'll set it ToString because remember cookies always store information as a string value. One of the other commonly used features of cookies is to set an expiration date and time for the cookie, and the way you do that is to access the cookie and set a particular property related to expiration. Let's get out this cookie that we have here. We'll say Response.Cookies("LastVisit") and then we're going to set the Expires property, and this is a date/time so we're going to set this equal to Datetime.Now.AddDays and we'll set that to 1. So what is going to happen here is this cookie called LastVisit will expire 1 day from the current time. As far as how this expiration works in that the data stored in the cookie down on the user's hard disk and then the next time that the user opens up the browser and visits this website the browser looks at the expiration date of the cookie and if the date has passed then the browser would delete the cookie from the user's hard disk. There's another approach to doing what we just did up above where we access the cookies collection directly and that is to create an instance of the cookie class, so we'll dimension a variable we'll call cookie as an HttpCookie and we'll set that equal to a new HttpCookie and here we specify the name of the cookie. In this case we'll call it LastVisit. That creates the cookie. Then we set the same properties that we set above. We'll go cookie.Value and we'll set that equal to Datetime.Now.ToString, and we'll set the Expires property. We'll set that to 1 day in the future. Set that to 1. Then what we need to do is to add this cookie to the cookies collection in the Response object, so we just go Response.Cookies.Add, pass in the cookie instance that we created and then this set of statements is equivalent to the first one where we accessed the cookie directly. You can store multiple cookies for the same user so what we'll do is add a second cookie here. We'll use the Response object—that cookies collection directly— and we're going to store the user ID and the value and we're going to set that let's say equal to 10. I'll have it expire the same as the first cookie. We'll say ("UserID").Expires and we'll set that equal to datetime.Now.AddDays(1). So now we have 2 cookies down on the user's machine; one storing the information for last visit and the other storing the user ID. One of the things you'll find is that if you store just 1 piece of information in a cookie you're going to use up the allotment of 20 cookies per website fairly quickly, so you can take advantage of another feature of cookies and that is you can store multiple values in the same cookie or, as they are called, subkeys. To store last visit and user ID in subkeys we would do it as follows: We'll take the Response object Cookies collection and this time we're going to name the cookie UserData, and then we're going to implicitly access and create a subkey called LastVisit and we'll assign to that the Datetime.Now.ToString, and then for the user ID we go Response.Cookies, same cookie, UserData, but we'll do a different subkey, and this one will be UserID, and this one we'll assign a value of 10. Then we can set the expiration date to this single cookie. We'll say UserData and set the Expires property equal to datetime.Now.AddDays(1), and this would have a single cookie with the 2 values expiring 1 day from now. As you might see, there is an advantage to storing multiple values in a cookie in that it contains or packages them up and also you only have to set the expiration date once, and that expiration date applies to all the values or subkeys that reside in the cookie. You can create this using other syntax up above so we can dimension a cookie—and we'll call this "cookie 1"— as an HttpCookie equal to a new HttpCookie and we'll call this UserData and then in cookie1.Values— not value, but values—and here we can set the last visit equal to the datetime.Now.ToString. We can set cookie1.Values("UserID") = "10" and we can set the expiration. We'll set that, again, to now and add 1 day. Then we add that to the Response.Cookies collection. Add, and we'll add (cookie1). Again, that is equivalent to accessing the cookies collection directly. The next thing we're going to look at is controlling the scope of the cookies, and by that I mean all the cookies associated with a website are sent up to the server every time a user requests any page in the website; however, you can restrict what cookies are sent to a particular part of the website and that's called scoping cookies. There are 2 ways that you can scope cookies. The first is to scope a cookie to a particular path. Let me take one of the cookies that we created previously. Let's just take this one here starting on line 22, and we'll paste it down below, and we'll change it from cookie1 to cookie2. Then what we're going to do with this cookie2 is we're going to set the path property that will restrict this cookie to a particular path on the website. We'll just change it one more time. Now if we take cookie2, and before we add it what we're going to do is we're going to take cookie2 and we're going to set the path property— now this can be set to a physical path or a virtual path underneath the website root. So in this particular case let's set I to "/Admin." What would happen here with cookie2 is that it is only visible to web pages in the admin folder and below. If the page that is requested by the user is in the admin folder they will get cookie2 sent back up to the server; however if the page they are requesting is say in the root of the website or in another subfolder off the root on the website they would not get cookie2 . One of the other ways you can scope a cookie is to a domain. So let's take our cookie1 and we'll copy and paste it down below. Let me just change that from cookie1 to cookie3— change all that—and now what we can do is, down here after the Expires property, we can set a property called Domain. We'll take cookie3 and we'll go to domain. What you can do here is you can set the domain to a specific subdomain because by default whenever a user requests a page from on the website all the cookies for the entire domain are sent back up to the server, but if we set the domain it restricts it, much in the same way that a particular path setting restricts what cookies are sent back. Let's set the domain to "" and in this case what's going to happen is that cookie3 will only be sent back up to the server if the page is associated with the subdomain Now in this particular case we're setting the domain to a specific subdomain called "support" within We could also set the domain equal to just and then that will restrict the cookie to the domain and any subdomains that exist within So that's a variation on using the domain property. Next we're going to look at how to read cookies when they're sent from the user's browser, through the user's browser from their hard disk back up to the server. In order to do that what I want to do is go over here and on default ASPX let's put in the design mode and just add a label control so we have somewhere to put information that's coming from the cookies. So go on to here, we'll take a label, drag and drop that onto our design mode surface for default ASPX. Now we'll go back into the code. Now that we have that label control on the page, in order to read the cookie it's pretty much the same as when we wrote the cookie. We'll just say if not, and the cookies come up in the request object in a cookies collection, and what we're doing here is testing to see first whether the cookie exists because it could have been deleted down on the user's computer. We'll get out the LastVisit cookie which we wrote previously, and we'll say is not Nothing then— so in this case we'll know the cookie exists and then we'll say label1.Text, and we'll assign to that the value of Request.Cookies("LastVisit").Value, which we had stored previously. A good practice, since the cookie could have been tampered with between the time we wrote it and it coming back up to the server, what we're going to do I take this text that's stored inside the cookie, and we're going to go Server.HtmlEncode, and that will help prevent any malicious code from being executed here on our server. We can also do a very similar approach before by defining an actual instance of the cookie object. Let me just copy what we had, paste it down here, and we'll get rid of this line, and if we know the cookie exists then what we can do is we can dimension. That will be cookie4 in this case as an HttpCookie, and we can set that equal to the Request.Cookies("LastVisit") there, and let me just change that to a capital L again. Once we have that then we can take our label1.Text and we can set that equal to server.HtmlEncode(cookie4.Value) and that would be equivalent to the previous statement. We can also access the subkeys in much the same way that we wrote them. So we could say if not request.Cookies— we'll take the user data which we wrote down to the user's hard disk previously— is nothing then once we know that cookie exists we can say label1.Text=Server.HtmlEncode. We can go at the (requestCookies("UserData") ("LastVisit")) and close off with our final parenthesis. This would access the LastVisit subkey and we could access any other subkeys in a cookie in the same manner. In addition to accessing the subkey value directly, we could get at it through the Values property of the cookie, and that property is actually a NameValueCollection so we could dimension a local variable. We could, for example, say dim cookieCollection equal to—or rather as a System.Collections.Specialized.NameValue Collection and assign to that the Request.Cookies, get the UserData cookie, and then take the Values property. Then, using that local variable which contains the subkeys, we could say label1.Text=server.HtmlEncode(cookieCollection, and then the name of the subkey— let's say LastVisit—and that is just a different way to approach getting at the subkeys. One other thing that you might want to do is modify the value or the expiration date of a cookie, and you can't actually take an existing cookie and modify either the value or the expiration date, but what you can do is create a new cookie of the same name, change the value or the expiration date and then add it to the cookies collection and it would override the existing cookie. For example, let's say we wanted to update the LastVisit cookie. What we could do is we could say Response.Cookies("LastVisit") and set the value, and we could set this to the current date/time, so we could say datetime.Now.ToString, and then we could say Response.Cookies("LastVisit"). Expires, set that equal to datetime.Now.AddDays(1) and that would update the last cookie value currently down on the user's computer. Deleting a cookie is actually very similar to modifying a cookie. Again, you can't directly access the cookie on the user's hard disk so what we could do is change the expiration date to a date prior to the current time and then the browser would think that the time for expiration of the cookie had already passed and it would automatically delete it. So you would do something like this. You would say Response.Cookies—let's say we're going at the LastVisit cookie and the Expires property and we would set that equal to datetime.Now.AddDays, and we would put a minus 1, which would make it 1 day earlier than the current date/time. That would cause the browser to delete that particular cookie. As far as subkeys are concerned, modification of subkeys is essentially writing a new value to the subkey, so in the case of the user data LastVisit cookie what we would do is say Response.Cookies.—

Video Details

Duration: 20 minutes and 52 seconds
Country: United States
Language: English
License: All rights reserved
Genre: None
Views: 6
Posted by: neudesicasp on Aug 26, 2013

In this video Chris Pels will show how to read, write, and delete cookies in an ASP.NET application. First, learn the basic operations for manipulating cookies. Then learn approaches to storing multiple values in a single cookie using name-value pairs called subkeys. Next, learn how to limit the scope of cookies to a particular application domain or folder. See how to modify values and expiration dates in existing cookies and how to delete an existing cookie. In addition, several considerations for using cookies are also discussed.

Caption and Translate

    Sign In/Register for Dotsub to translate this video.