All aspects of cookies (basic/Advanced) deep Understanding _ Practical skills

Source: Internet
Author: User
Tags httpcontext trim ssl connection

First, the preface

Cookies must be known to everyone, but not everyone is proficient. This article explains the various aspects of cookies.

Second, basic knowledge

1. What is a cookie

A Cookie is a small piece of textual information that accompanies the user request and the page is passed between the WEB server and the browser. Cookies contain information that the WEB application can read every time a user accesses the site.

For example, when a user requests a page in a Web, the application sends the user more than one page and a cookie containing the date and time, and the user's browser obtains the cookie and stores it in a folder on the user's hard disk.

Later, if the user requests a page in your site again, when the user enters a URL, the browser looks for the Cookie associated with the URL on the local hard disk. If the cookie exists, the browser sends the cookie to your site along with the page request. The application can then determine the date and time that the user last visited the site. You can use this information to display a message to the user or to check the expiration date.

Cookies are associated with a Web site, not with a particular page. Therefore, the browser and the server Exchange Cookie information regardless of which page in the site the user is requesting. When users visit different sites, each site may send a cookie to the user's browser, and the browser stores all cookies separately.

Cookies Help the Web site store information about visitors. In general, cookies are a way of keeping WEB application continuity (that is, performing state management). The browser is disconnected from the WEB server, except for a short period of actual exchange of information. For each request that a user makes to a Web server, the Web server handles it separately. However, in many cases, it is useful for a WEB server to identify users when they request a page. For example, a Web server on a shopping site tracks every shopper so that the site can manage shopping carts and other user-specific information. As a result, cookies can serve as a business card that provides relevant identification information to help the application determine how to proceed.

Cookies can be used for a variety of purposes, all of which are designed to help the site remember users. For example, a site that implements a poll can simply use the Cookie as a Boolean value to indicate whether the user's browser has participated in the vote, so that the user cannot vote for the second time. A site that requires a user to log on can use a Cookie to record that the user is logged in, so that the user does not have to enter credentials each time.

2.Cookies How to store

Cookies are saved on the user's local machine, and different browsers are stored in different folders, and are saved separately by domain name. That is, cookies between websites do not cover each other.

Users of IE browsers can find cookies txt files in their local documents, and Windows Server 2003/xp are stored in different operating system locations:

C:\Documents and Settings\administrator\cookies folders.

The name txt is saved according to the domain name, such as cookies under the localhost domain:

Administrator@localhost[1].txt or Administrator@localhost[2].txt.

The following [1] and [2] are alternately changing with each save.

3.Cookies How to pass

Information about cookies is passed between the Web server and the browser. Saved in the HTTP request.

(1) Request page

In the HTTP header requesting a page, the local cookie information that belongs to the page is added to the HTTP header, and note the following bold section:

Copy Code code as follows:

Get/cookies/test.aspx http/1.1
host:localhost:1335
user-agent:mozilla/5.0 (Windows; U Windows NT 5.2; ZH-CN; rv:1.9.1.1) gecko/20090715 firefox/3.5.1 GTB5 (. NET CLR 3.5.30729)
accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language:zh-cn,zh;q=0.5
Accept-encoding:gzip,deflate
accept-charset:gb2312,utf-8;q=0.7,*;q=0.7
keep-alive:300
Connection:keep-alive
Cookie:my.common.testcookieinfo=pkid=999&testvalue=aaabbbcccdddeee

(2) page Response

If the page requires the cookie information to be written, the HTTP returned is as follows, note the bold section:

Copy Code code as follows:

http/1.x OK
Server:ASP.NET Development server/9.0.0.0
Date:thu, Aug 2009 03:40:59 GMT
x-aspnet-version:2.0.50727
set-cookie:my.common.testcookieinfo=pkid=999&testvalue=aaabbbcccdddeee; Expires=fri, 07-aug-2009 03:40:59 GMT; path=/
Cache-control:private
content-type:text/html; Charset=utf-8
content-length:558
Connection:close

4.Cookies How to view

(1) Check the TXT file of cookies

IE users can view the TXT file of cookies directly.
For example: C:\Documents and Settings\administrator\cookies\administrator@localhost[1].txt

(2) using Plug-ins

The use of web Developer plugins under FF makes it easy to view, delete, and modify cookies:

Plugin screenshot:

View Page Cookies:

Three. Cookies Advanced knowledge

1.Cookie limit

Most browsers support cookies with a maximum of 4096 bytes.

Browsers also limit the number of cookies that a site can store on a user's computer. Most browsers allow only 20 cookies per site; note that 20 of these are primary key values, or 20 cookies, but each cookie record can contain several subkeys, which are explained in detail below. If you try to store more cookies, the oldest cookies are discarded. Some browsers also have an absolute limit of the total number of cookies they will accept from all sites, usually 300.

2.Cookies storage Format

Cookies can contain a primary key, and the primary key then contains subkeys. For example, the format for obtaining cookies in asp.net is:

Copy Code code as follows:

Request.cookies[key][subkey]. ToString ();

The key is the primary key, and subkey is the subkey associated with the primary key.

(1) Local Disk storage format:

Copy Code code as follows:

My.Common.TestCookieInfo
Pkid=999&testvalue=aaabbbcccdddeee
localhost/
1536
3059603968
30021392
2348960464
30021191
*

The pkid=999&testvalue=aaabbbcccdddeee is the value of the cookie, which is included in the Subkey=subvalue format, so the cookie contains a subkey.

(2) cookie format in JavaScript

The cookie given in JavaScript is a string that is obtained by document.cookies. The character format is as follows:

My.Common.SubKey=pkid=999&testvalue=aaabbbcccdddeee; Singlekey=singlekeyvalue

The above string contains two cookies, one is a singlekey that contains no subkeys, one is a My.Common.SubKey containing Pkid and TextValue two subkeys, and two cookies pass ";" Segmentation.

(3) cookie format in asp.net

As with all server-side languages, the collection class is used in asp.net to save cookies:

Copy Code code as follows:

public sealed class Httpcookiecollection:nameobjectcollectionbase
{...}

Cookies for the current page can be obtained and written through the cookies properties of the Httpresquest and HttpResponse objects.

3.Cookies Content Encoding Format

The value of a cookie can be saved except for ";" Outside of the punctuation. but you can't save Chinese characters. Save Chinese characters will appear garbled.

So for the content of cookies to be unified coding and decoding. In order to decode and encode on both the browser and server side, the UTF encoding format is used uniformly.

This is mainly because JavaScript can only use the UTF encoding format.

The Path property of 4.Cookies

The path attribute of cookies means that the current cookies can be used on the site's path.

For example, the following two cookies with the same name:

Allow two cookies with the same name but different path.

For both the server side and the client, give priority to the cookies below the path on this page when acquiring.

That is, if the page below the/chapter10/path gets the value of the cookie TestKey, only the testValue222222 value can be obtained.

Expiration time of 5.Cookies

If a cookie is not set to expire when it is saved, the cookie expires as "current browser process is active", which is the same as session closure after the browser disappears. in asp.net, you can also specify that this cookie will take effect for following browsers by setting the expiration time of the HttpCookie object to Datetime.minvalue. (This is not easy to say, Ah, in the head and other people's help to find.) )

If the expiration time is set and is greater than the current time, the cookie value is saved.

If the expiration time is set but is less than or equal to the current time, the cookie value is cleared.

6.Cookies and Session

Sometimes we ignore the relationship between cookies and session. But the two are inseparable.

The only indication of session: SessionID is usually stored in cookies (or stored in a URL). For ASP.net, SessionId is saved in a cookie with a key value of "Asp.net_sessionid", as shown in figure:

Because the amount of cookies stored is limited, our system must be careful to keep cookies away from getting rid of this key cookie. In the best practices described below, this cookie is specially handled in the code for storing cookies in a strong object way.

7.Cookies encryption

When setting the properties of cookies, there is an option secure to control the encryption characteristics of the cookie.

True if the Cookie is transmitted over an SSL connection (HTTPS), otherwise false. The default is False.

If we save a cookie and set it up, then in a non-HTTPS page, this cookie is not available on either JavaScript or server side. However, the presence of this cookie can still be seen locally.

8.Cookies and Ajax

If AJAX requests access to a server page, this server page can write cookies and session to the user's browser.

Four. Cookies Best Practices

After understanding the relevant knowledge of cookies, the following is the best event method. This includes both client and server-side components.

(1) Storing cookies in asp.net

Typically, we use the request and response objects to manipulate cookies directly:

Write cookies:

Copy Code code as follows:

response.cookies["K1"]. Value = "K1value";
response.cookies["K2" ["k2-1"] = "k2-1value";
RESPONSE.COOKIES.ADD (New HttpCookie ("K3", "K3value"));

Read cookies:
Copy Code code as follows:

request["K1"];
request.cookies["K1"]. Value;
request.cookies["K2" ["k2-1"];
Request.Cookies.Get (0). Value;

Note that the request["K1"] is a familiar way of getting get and post parameters, while also being able to get the value of cookies!

In addition, some of the above statements must be accessed through the Value property, while others are not required.

(2) Storing cookies in the form of objects

Here is a tool class that can save cookies as a whole in an object way. and takes up only one cookie, all attributes are on subkeys.

Source:

Copy Code code as follows:

<summary>
Cookies base class. The data class that will need to store cookies is derived from this class and can be saved and read by a strongly typed object in a cookie.
</summary>
<remarks>
2009.8.6 Ziqiu.zhang Created
</remarks>
<example>
Suppose Mycookiesinfo is getting objects from cookies:
<code>
Cookieinfo item = new Cookieinfo (); After new, the object has been constructed from cookies.
</code>
To save an object in a cookie:
<code>
Cookieinfo item = new Cookieinfo ();
Item.value = "Test value";
Item. Setcookies ("1"); Cookies are valid for 1 days
</code>
</example>
[System.serializable]
public class Cookieinfo
{
#region ==================== Constructed method ====================
<summary>
Constructors
</summary>
Public Cookieinfo ()
{
}
#endregion
#region ==================== Public Method ====================
<summary>
Get the expiration time of the current cookie
</summary>
<returns> Expiration Time </returns>
Public DateTime Getexpirestime ()
{
String cookiename = GetType (). ToString ();
if (Httpcontext.current.request.cookies[cookiename]!= null)
{
Return Httpcontext.current.request.cookies[cookiename]. Expires;
}
return datetime.minvalue;
}
<summary>
Save cookies, expiration time for browser shutdown is invalid.
</summary>
<param name= "Expirestime" >cookies expired events </param>
<returns> whether to save success </returns>
public bool Save ()
{
return this. Save (Datetime.minvalue);
}
<summary>
To save cookies, you need to specify an expiration time.
</summary>
<param name= "Expirestime" >cookies expired events </param>
<returns> whether to save success </returns>
public bool Save (DateTime expirestime)
{
String cookiename = GetType (). ToString ();
HttpCookie Sessioncookie = null;
Make a backup of the SessionId.
if (httpcontext.current.request.cookies["Asp.net_sessionid"]!= null)
{
String Sesssionid = httpcontext.current.request.cookies["Asp.net_sessionid"]. Value.tostring ();
Sessioncookie = new HttpCookie ("Asp.net_sessionid");
Sessioncookie.value = Sesssionid;
}
Set the cookie expiration time.
DateTime dtexpiry = expirestime;
Httpcontext.current.response.cookies[cookiename]. Expires = Dtexpiry;
Set the cookie domain name.
String domain = string. Empty;
if (httpcontext.current.request.params["http_host"]!= null)
{
Domain = "www.elong.com";
Domain = httpcontext.current.request.params["http_host"]. ToString ();
}
If it is a www.elong.com or multilevel domain name, it needs to be translated into elong.com
if (domain. IndexOf (".") >-1)
{
string[] temp = domain. Split ('. ');
if (temp. Length >= 3)
{
Domain = temp[temp. Length-2]. Trim () + "." + temp[temp. LENGTH-1]. Trim ();
}
Httpcontext.current.response.cookies[cookiename]. domain = domain;
}
Writes the properties of the class to the cookie.
propertyinfo[] Propertys = GetType (). GetProperties ();
foreach (PropertyInfo pi in Propertys)
{
Object OJ = Pi. GetValue (this, null);
Type type = Pi. PropertyType;
String valuestr = String. Empty;
if (OJ!= null && OJ. ToString ()!= string. Empty)
{
if (type = = Type.GetType ("System.DateTime"))
{
Valuestr = ((DateTime) OJ). ToString ("Yyyy/mm/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
Else
{
Valuestr = OJ. ToString ();
}
Httpcontext.current.response.cookies[cookiename][pi. Name] = Httputility.urlencode (VALUESTR);
}
}
If the total number of cookies exceeds 20, rewrite Asp.net_sessionid to prevent session loss.
if (HttpContext.Current.Request.Cookies.Count > && sessioncookie!= null)
{
if (Sessioncookie.value!= string. Empty)
{
HttpContext.Current.Response.Cookies.Remove ("Asp.net_sessionid");
HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Sessioncookie);
}
}
return true;
}
<summary>
Retrieve cookie Value
</summary>
public void Load ()
{
String cookievalue = String. Empty;
String cookiename = GetType (). ToString ();
Writes back to the property by traversing the property, retrieving the value from the cookie.
propertyinfo[] Propertys = GetType (). GetProperties ();
foreach (PropertyInfo pi in Propertys)
{
Try
{
Cookievalue = Httputility.urldecode (httpcontext.current.request.cookies[cookiename][pi. Name]. ToString ());
}
Catch
{
Cookievalue = string. Empty;
}
if (pi. CanWrite && cookievalue!= null && cookievalue!= string. Empty)
{
Try
{
Object OBB = Cookievalue;
Type type = Pi. PropertyType;
Obb = Convert.changetype (Obb, type);
Pi. SetValue (this, OBB, null);
}
Catch {}
}
}
}
#endregion
}


Use

First, explain how to use this class.

Create a model for the classes that you want to keep in the cookies and inherit from the Cookieinfo. For example, the following establishes the Mycookieinfo class, which contains attributes Pkid,testvalue and Testdatetime:

Copy Code code as follows:

<summary>
Data Objects for storing cookies
</summary>
[System.serializable]
public class Mycookieinfo:cookieinfo
{
private int m_pkid = 0;
public int Pkid
{
Get
{
return m_pkid;
}
Set
{
M_pkid = value;
}
}

private string m_testvalue = "";
public string TestValue
{
Get
{
return m_testvalue;
}
Set
{
M_testvalue = value;
}
}

Private DateTime m_testdatetime = DateTime.Now;
Public DateTime Testdatetime
{
Get
{
return m_testdatetime;
}
Set
{
M_testdatetime = value;
}
}
}

You can then save and read cookies using the object's Save and load methods:
Copy Code code as follows:

• Save
The Save method has two overloads, and the Save method without parameters indicates that the cookie expires at the same time as the browser, that is, the cookie disappears when the browser closes. Otherwise, you will need to pass in the cookie expiration time.
Mycookieinfo testcookies = new Mycookieinfo ();
Testcookies.pkid = 1;
Testcookies.testvalue = "Chinese test";
Testcookies.save (); • Read

Mycookieinfo testcookies = new Mycookieinfo ();
Testcookies.load ();
This.lblMsg.Text = "Pkid:" + testCookies.Pkid.ToString ();
This.lblMsg.Text + = ", TestValue:" + testCookies.TestValue.ToString ();
This.lblMsg.Text + = ", Testdatetime:" + testCookies.TestDateTime.ToString ("Yyyy/mm/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

Now we can read and save cookies for a strongly typed object.
(3) using JavaScript to manipulate cookies

We also need to operate cookies on the client.

The following is a packaged jquery tool function designed to operate cookies.
Of course, this tool function can be changed to a standard JavaScript function by slightly modifying it.

Download Address

Tool Function Description:

Method signature: Jquery.cookie (name, subname, value, options)

Method Description: Read, write, delete cookies

Method Parameters:

Name Description Example
Name The primary key value of cookies Read PRIMARY key:
$.cookie ("Singlekey")

Write cookies with a value of string:
$.cookie ("Singlekey", "" "," Singlekey-value ", {expires:1, Path:"/", Secure:false})
SubName The child key name. Please pass NULL or NULL when writing Read subkeys:
$.cookie ("Multikey", "subName1")

Write cookies, value as object:
var subnameobj = {subName1: "AAA", SubName2: "BBB", SubName3: "CCC"};$.cookie ("Multikey", "", Subnameobj, {expires:1, Path: "/", secure:false});
Value Cookie value, which can be a string or object.
If it is an object, each property of the object is saved in the cookie subkey.
See the example above.
options parameter:
Expires: Can be a number or a data type object. The
If an incoming number indicates a few days after expiration. The
Path: path, which defaults to the domain name root ("/").
Secure: Enable encryption, default to No.



To specify expiration time:

var mydate = new Date (); Mydate.setfullyear (2009, ten); $.cookie ("Singlekey" , "", "Singlekey-value", {expires:mydate, secure:false})  

Expires after 1 days:

var time = Date (); $.cookie ("Singlekey", " "," Singlekey-value ", {expires:1, Path:"/", Secure:false})

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.