Cookies (translated) in ASP.

Source: Internet
Author: User
Tags allkeys cookie names time and date urlencode subdomain

Cookie (translated) cookie in ASP.
    • A cookie is a small text message that is carried when requesting a server or accessing a Web page.

Cookies provide a way for a Web application to store specific user information. The value of a cookie is a string type and is visible to the user.

    • Cookies Exchange data with each other Request and Response between the browser and the server.

If a user requests a page on the server, the server returns a cookie containing the date and time in addition to the requested page. This cookie is stored on a folder on the user's hard disk. Later, if the user accesses the server again, when the user enters the URL, the browser will view the cookie associated with the URL on the local hard drive. If a cookie exists, the browser sends the cookie along with the request. The server can then read the cookie information sent over, the date and time the user last visited the site. You can use this information to display a message to the user, or to check for an expiration date.

    • Cookies are associated with a specific site

Cookies are associated with a Web site, not a specific page, so the browser and server Exchange cookie information regardless of what page the user requests from your server. The browser stores cookies for each different Web site, ensuring that each cookie corresponds to a specific Web site.

    • Cookie keeps session state

Cookies can help the server store information about visitors. In layman's words, cookies are a way to maintain the continuity of Web applications, that is, session state management. Because HTTP requests are stateless, some column requests do not know which users the request is from, so cookies can be used to uniquely identify the user and maintain session state.

Cookies are used for many purposes, all of which are related to helping the site remember users. For example, a polling site might use a cookie as a Boolean value to indicate whether the user's browser is already voting, so that the user cannot vote two times. A Web site that requires users to log on may use cookies to record a user's login, so that users do not have to continue to enter credentials.

Cookie Restrictions

Most browsers support up to 4096 bytes of cookies. Because of this limitation, cookies are best used to store small amounts of data, or, better yet, identifiers such as user IDs.

Browsers also limit how many cookies a Web site can store on a user's computer. Most browsers only allow 20 cookies per site. If you want to store more, the old cookie will be discarded. Some browsers also limit the total number of cookies (site-insensitive).

Although cookies are useful for Web applications, applications should not rely on cookies. Do not use cookies to support critical sensitive data.

Write a cookie

The browser is responsible for managing cookies on the user's computer. A cookie HttpResonse is sent to the browser via an object that exposes a collection called cookies. Any cookie that you want to send to the browser must be added to this collection. When creating a cookie, specify a name and value. Each cookie must have a unique name so that it can be recognized by the browser when it is read. Because cookies are stored by name, the new cookie value is overwritten by the same number of cookie names.

You can set the date and expiration time of the cookie. When a user accesses a site where a cookie is written, the browser deletes the expired cookie. A cookie may be valid for 50 years.

If you do not set a cookie expiration time, a cookie is created, and it is not stored on the user's hard disk. This cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored in a short time, or it should not be written to a disk on the client computer for security reasons. For example, a non-persistent cookie is useful if a user is using a public computer and does not want to write a cookie to disk.

You can add cookies to a collection of cookies in a variety of ways. The following example shows two ways to write a cookie:

//第一种Response.Cookies["userName"].Value = "patrick";Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);//第二种HttpCookie aCookie = new HttpCookie("lastVisit");aCookie.Value = DateTime.Now.ToString();aCookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(aCookie);

The example adds two cookies to the cookie collection, one named user name and the last access time. For the first method, the value of the cookie collection can be read and written directly. Because the cookie inherits from NameObjectCollectionBase the collection type, the cookie can be obtained directly.

For the second method, create an instance of the HttpCookie object, set its properties, and add it to the cookie collection by using the Add method. The name of the cookie is added through the constructor function.

Both of these examples complete the same task of writing a cookie to the browser. In both of these methods, the expiration value must be a datetime type. Because all cookie values are stored as strings, datetime values are converted to strings.

Cookies with multiple values

A cookie can store a value, such as a user name or last access. You can also store multiple key-value pairs in a cookie. Key-value pairs are called sub-keys. (The layout of the child keys is very similar to the query string in the URL.) For example, you can create a cookie named UserInfo that has child health username and lastvisit instead of creating two separate cookies.

Zijian can place relevant or similar information into a cookie. If all information is in one cookie, the cookie attribute, such as expiration, will be applied to all information. (Conversely, if you want to assign different expiration dates to different types of information, you should store the information in a separate cookie.) )

Cookies with sub-keys can also help limit the size of cookie files. As mentioned earlier, cookies are typically limited to 4096 bytes, and each site can store more than 20 cookies. By using a cookie with a subkey, you can reduce the limit on the number of site cookies. In addition, a cookie itself takes up about 50 characters (expiration information, and so on), plus the length of the value you store in it, all of which point to a 4096-byte limit. If you store 5 subkeys instead of 5 separate cookies, you can save the cost of a single cookie, and you can save about 200 bytes.

To create a cookie with a child key:

//第一种Response.Cookies["userInfo"]["userName"] = "patrick";Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);//第二种HttpCookie aCookie = new HttpCookie("userInfo");aCookie.Values["userName"] = "patrick";aCookie.Values["lastVisit"] = DateTime.Now.ToString();aCookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(aCookie);
Cookie Scope

By default, all cookies that have an expiration time on a site are stored on the client's hard disk, and all cookies are sent to the server when the site is requested. In other words, every page on the site has access to all cookies on that site. However, there are two ways you can limit the scope of cookies:

    • Limits the scope of a cookie to a folder on the server, which allows you to restrict cookies to an application on the site.

    • Setting the scope to a domain allows you to specify which subdomains in the domain can access cookies.

To restrict a cookie to a folder on the server, you can set the Path property of the cookie, as in the following example:

HttpCookie appCookie = new HttpCookie("AppCookie");appCookie.Value = "written " + DateTime.Now.ToString();appCookie.Expires = DateTime.Now.AddDays(1);appCookie.Path = "/Application1";Response.Cookies.Add(appCookie);

A path can be either a physical path under the site root or a virtual path. The effect of this is that the cookie is only available for pages in the Application1 folder or virtual root directory. For example, if your site is www.contoso.com, the cookie created in the previous example can be associated with a path http://www.contoso.com/Application1/ page, any page under that folder. However, cookies do not have pages that are available in other applications, such as http://www.contoso.com/Application2/ or http://www.contoso.com/ .

Limitations and scopes of cookies

By default, a cookie is associated with a specific domain.
For example, if your site is www.contoso.com, the cookie you write will be sent to the server when the user requests any page of that site.
(This may not include cookies with a specific path value.) )
If your site has sub-domains, such as contoso.com,sales.contoso.com, and support.contoso.com, then you can associate cookies with specific sub-domains.

code example:

Response.Cookies["domain"].Value = DateTime.Now.ToString();Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);Response.Cookies["domain"].Domain = "support.contoso.com";

When the domain is set in this manner, the cookie will only be available for pages in the specified subdomain. You can also use domain properties to create a cookie that can be shared across multiple subdomains, as shown in the following example:

Response.Cookies["domain"].Value = DateTime.Now.ToString();Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);Response.Cookies["domain"].Domain = "contoso.com";

At this point, the cookie can be either a primary domain or a subdomain such as sales.contoso.com and support.contoso.com.

Read cookies

When the browser makes a request to the server, the cookie is sent to the server along with the request. In your application, you can use HttpRequest to read cookies.

code example:

if(Request.Cookies["userName"] != null){    HttpCookie aCookie = Request.Cookies["userName"];    var cookiText = Server.HtmlEncode(aCookie.Value);}

Before attempting to obtain the value of a cookie, you should ensure that the cookie exists and that if the cookie does not exist, you will get an NullReferenceException exception. Also note that the HTMLEncode method is called to encode the contents of a cookie. This ensures that the malicious user does not add the executable script to the cookie.

Reading the value of a subkey in a cookie is similar to setting it. The following code example shows a way to get a sub-key value

if(Request.Cookies["userInfo"] != null){    var name =         Server.HtmlEncode(Request.Cookies["userInfo"]["userName"]);    var visit =        Server.HtmlEncode(Request.Cookies["userInfo"]["lastVisit"]);}

Reads the value of the key-value pair lastvisit, which was previously set to the DateTime type. However, the cookie stores the value as a string, so if you want to use the value of lastvisit as a date, you must convert it to the appropriate type.

Such as

DateTime dt= DateTime.Parse(Request.Cookies["userInfo"]["lastVisit"]);

The subkey in the cookie is the NameValueCollection type. Therefore, another way to get a subkey is to get the child key collection and then extract the subkey values by name, as shown in the following example:

if(Request.Cookies["userInfo"] != null){    System.Collections.Specialized.NameValueCollection  UserInfoCookieCollection;    UserInfoCookieCollection = Request.Cookies["userInfo"].Values;   var name =         Server.HtmlEncode(UserInfoCookieCollection["userName"]);    var visit =        Server.HtmlEncode(UserInfoCookieCollection["lastVisit"]);}
Expiration time of the cookie

The browser is responsible for managing the expiration time and date of the Cookie,cookie to help the browser manage its stored cookies. Therefore, although you can read the name and value of the cookie, you cannot read the cookie's expiration date and time. When the browser sends cookie information to the server, the browser does not contain expiration information. (The Expiration property of a cookie always returns a DateTime value of 0.) If you are concerned about the expiration date of the cookie, you must reset it.

Read the cookie Collection

Get all the Cookies

code example;

System.Text.StringBuilder output = new System.Text.StringBuilder();HttpCookie aCookie;for(int i=0; i<Request.Cookies.Count; i++){    aCookie = Request.Cookies[i];    output.Append("Cookie name = " + Server.HtmlEncode(aCookie.Name)         + "<br />");    output.Append("Cookie value = " + Server.HtmlEncode(aCookie.Value)        + "<br /><br />");}

There is a deficiency in the previous example, and if the cookie has a subkey, the subkey is displayed as a single name/value string. You can read the Haskey property of a cookie to determine if the cookie has a child key. If so, you can read the child key collection to get a separate subkey name and value.
You can also read sub-key values directly from the value collection by index values. The corresponding subkey name can be found in the AllKeys member of the value collection, which returns an array of strings. You can also use the value collection's key value. However, the AllKeys property is cached the first time it is accessed. Instead, the key property constructs an array on each access. For this reason, the AllKeys property is much faster in the context of the same page request.

The following example shows the modification of the previous example. It uses the HasKeys property to test the sub-key, and if a subkey is detected, the example obtains a subkey from the value collection:

for(int i=0; i<Request.Cookies.Count; i++){    aCookie = Request.Cookies[i];    output.Append("Name = " + aCookie.Name + "<br />");    if(aCookie.HasKeys)    {        for(int j=0; j<aCookie.Values.Count; j++)        {            subkeyName = Server.HtmlEncode(aCookie.Values.AllKeys[j]);            subkeyValue = Server.HtmlEncode(aCookie.Values[j]);            output.Append("Subkey name = " + subkeyName + "<br />");            output.Append("Subkey value = " + subkeyValue +                 "<br /><br />");        }    }    else    {        output.Append("Value = " + Server.HtmlEncode(aCookie.Value) +            "<br /><br />");    }}

Alternatively, you can extract the subkey as a NameValueCollection object, as shown in the following example:

System.Text.StringBuilder output = new System.Text.StringBuilder();HttpCookie aCookie;string subkeyName;string subkeyValue;for (int i = 0; i < Request.Cookies.Count; i++){ aCookie = Request.Cookies[i]; output.Append("Name = " + aCookie.Name + "<br />"); if (aCookie.HasKeys) { System.Collections.Specialized.NameValueCollection CookieValues = aCookie.Values; string[] CookieValueNames = CookieValues.AllKeys; for (int j = 0; j < CookieValues.Count; j++) { subkeyName = Server.HtmlEncode(CookieValueNames[j]); subkeyValue = Server.HtmlEncode(CookieValues[j]); output.Append("Subkey name = " + subkeyName + "<br />"); output.Append("Subkey value = " + subkeyValue + "<br /><br />"); } } else { output.Append("Value = " + Server.HtmlEncode(aCookie.Value) + "<br /><br />"); }}
Cookie deletion and modification cookies

You cannot modify the value of a cookie directly after it has been acquired because the cookie is stored on the user's hard disk (request.cookies["Key"). Value= "Some", which is not working here), must be in response.cookies["Key"]. Value= "Somenew" can only be modified. In fact, the new value of the cookie set in the server, overwriting the old value of the cookie on the user's browsing ground.

code example:

int counter;if (Request.Cookies["counter"] == null)    counter = 0;else{    counter = int.Parse(Request.Cookies["counter"].Value);}counter++;Response.Cookies["counter"].Value = counter.ToString();Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);
Delete Cookies

The cookie is removed from the user's hard disk and the principle of cookie modification is the same. Cookies cannot be deleted directly because the cookie is on the user's hard drive. However, you can create a new cookie with the same name as the cookie you want to delete, but set the cookie's expiration time to a date earlier than today. When the browser checks the expiry time of the cookie, the browser discards the outdated cookie.

code example:

HttpCookie aCookie;string cookieName;int limit = Request.Cookies.Count;for (int i=0; i<limit; i++){    cookieName = Request.Cookies[i].Name;    aCookie = new HttpCookie(cookieName);    aCookie.Expires = DateTime.Now.AddDays(-1);    Response.Cookies.Add(aCookie);}
Sub-key modification and deletion

Modifying a separate subkey is the same as creating it

Such as:

Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

To delete a separate subkey , you can manipulate the value collection of the cookie, which contains the subkeys.
First, get a specified cookie from the cookie collection and then call the Remove method of the cookie value collection, which is the name of the subkey to be deleted, and then add the cookie to the collection.

The following code example:

string subkeyName;subkeyName = "userName";HttpCookie aCookie = Request.Cookies["userInfo"];aCookie.Values.Remove(subkeyName);aCookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(aCookie);
Cookie Security

The security of a cookie is similar to getting data from the client. For an application, a cookie can be thought of as another form of user input. Because the cookie is stored on the user's own hard drive, the cookie is visible to the user and can be modified.

Because cookies are visible to users, they cannot store sensitive data in cookies, such as usernames, passwords, credit card numbers, and so on.

Since cookies are also modifiable, information obtained from cookies for the program also needs to be verified and judged. It is not easy to think that the data in a cookie is the same as the data we expect.

Cookies are sent as plain text between the browser and the server, and any person capable of intercepting web traffic can intercept cookies. However, you can set a cookie to be transmitted only if you use Secure Sockets Layer (SSL), which encrypts the cookie when it is transmitted. However, on the user's hard drive, the cookie is not protected by SSL.

Determine if the browser accepts cookies

The user can set the browser to reject cookies. If the cookie cannot be written, no error is thrown. Similarly, the browser does not send any information about the current cookie settings to the server.

Client Authentication

The simplest is to use JS to judge

  if (navigator.cookieEnabled{        alert("Cookie 可用");    }    else{        alert("Cookie 禁用");    }
Server-side validation

The cookie attribute does not indicate whether cookies are enabled. It only indicates whether the current browser natively supports cookies.

One way to determine whether a cookie is accepted on the server is to try to write a cookie and then try to read the cookie. If you cannot read the cookie you have written, you can assume that the browser has closed the cookie.

If there is no, please advise

Reference:

    • Msdn-cookie

Cookies (translated) in ASP.

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.