Asp. NET and JS interoperability issues with cookies
Recently the problem of the cookie wrapped for several days, because the project needs, both the client and server have to operate cookies, and server-side cookies are with subkeys, the previous do client read, set up and delete cookies code (lazy), are Google down, and are no subkeys form: Name=value format, so, in the absence of a thorough understanding of the cookie before the copy down the code for a little modification, it was used to their own web site to go, and finally very depressed, for several days have been a cookie read and write problems, There is no way, today to understand the knowledge of the cookie consolidated a few, only to find out why.
First look at the following cookie Concise reference: (from: http://www.builder.com.cn/2007/1024/576287.shtml)
One write Cookie
1. The Name and Value properties are set by the program, and the default values are null references.
2. The default value of the domain property is the domain name portion of the current URL, regardless of which directory the page in which the cookie is issued is.
For example, a cookie is emitted from the Http://www.cnblogs.com/bmwchampion/archive/2009/08/31/aspnet_js_cookie.html?opt=1 page, The Domain property defaults to http://www.cnblogs.com/bmwchampion/archive/2009/08/31/aspnet_js_cookie.html?opt=1, which can be set by the program to the desired value.
3. The default value of the Path property is the root directory, that is, "/" regardless of the directory in which the page in which the cookie is issued is sent. The program can be set to a certain path to further limit the scope of this cookie.
4. Expires property, this property sets the expiration date and time for this cookie. If you do not set a cookie's validity period (the default setting), you can also create a cookie, but it will not be saved to the user's hard disk, but rather become part of the user's session information, and the cookie will disappear when you close the browser or session timeout, which is called a non-persistent cookie. The cookie that holds the SessionID is such a cookie that it is not stored on the hard disk and only exists in memory.
5. The cookie to be issued is appended to the response's Cookie property to send this cookie to the client: Reponse.Cookies.Add (cookie)
6. Domain Property +path Property The same all cookies exist in a file on the client, and the cookie is split between the cookies with "*". The first line of each cookie is the name of the cookie, the second row is the value, and the third line is a string of the Domain property +path property that indicates the scope of the cookie, and the remaining lines contain the daily processing information for the cookie, such as the expiration date and time. There is also a simple checksum in the cookie, and if you change the cookie name or the length of the value, the browser detects the modification and deletes the cookie.
Two read cookies
1. The Request.Cookies property contains a collection of all cookies that the client sends to the server, and only cookies that are within the scope of the request URL are sent to the server along with the HTTP request.
2. The values of the Name and Value properties and subkeys are easily readable.
3. Domain and path attributes are not read, read domain property is always "", read the Path property is always "/". These properties were intended to be of limited use. If your page is not in the same domain as the cookie, you will not receive the cookie at all in the location of the page.
4. Also unable to read the expiration date and time of the cookie. In fact, when the browser sends Cookie information to the server, the browser does not include expired information. You can read the Expires property, but always return a date/time value of zero. The primary role of the Expires property is to help the browser perform day-to-day management of the Cookie store. From the server's point of view, the Cookie either exists or does not exist, so the expiration date is not useful information for the server.
Therefore, the browser does not provide this information when sending cookies. If you need a Cookie expiration date, you must reset it.
Three Modify and delete cookies
1. In fact, you cannot modify a cookie directly, create a cookie with the same name, and send the cookie to the browser to overwrite the old cookie on the client.
2. Similarly, you cannot delete a cookie directly, you can modify a cookie to allow the browser to help you delete the cookie, modify the cookie is valid for a certain time in the past, when the browser check the validity of the cookie, it will delete the expired Cookies.
The relationship between the four cookies and the session
1. asp.net session can take the cookie and cookieless two methods, cookieless way is to place the SessionID in the URL in the client and the server to the back and forth, do not need to use cookies, here is not discussed in this way.
2. The first time a client requests a URL in asp.net, the server generates a SessionID for the client and sends it to the client as a non permanent cookie.
3. Non-permanent cookies are only lost after the browser is closed, and the session timeout is the process:
3.1 The first time the client accesses the server, a SessionID is sent to the client with a non permanent cookie.
3.2 Access to this URL before the browser is closed, the browser will send this sessionid to the server, the service side according to the SessionID to maintain the customer's service side of the various states (that is, the various values saved in session), These sessions can be manipulated in a Web application.
3.3 The service side maintains the expiration time for this SessionID, and the session timeout can be set in IIS. Each request will cause the service side to extend the expiration time of this sessioid by one setting.
3.4 When the server discovers that a SessionID is obsolete, that a customer has not accessed the site again within the set timeout period, this sessionid, along with all session variables associated with this sessionid, is removed.
3.5 The client's browser does not shut down, do not know that the server has already deleted this SessionID, the client still sends this SessionID cookies to the server, only at this time the server has not recognized this sessionid, will this user as a new user, Assign a new SessionID again.
Then I put the client additions and deletions to the cookie code, and the server-side additions and deletions to the cookie code:
JS additions and deletions change cookies:
JS Operation Cookie Method! Write cookies function Setcookie (value, name, key) {var days = 2; var exp = new Date (); Exp.settime (Exp.gettime () + days * 2 4 * 60 * 60 * 1000); if (key = = NULL | | | key = = "") {Document.cookie = name + "=" + encodeURI (value) + "; expires=" + exp.togmtstring () + ";p ath=/ "; } else {var namevalue = GetCookie (name); if (Namevalue = "") {Document.cookie = name + "=" + key + "=" + encodeURI (value) + "expires=" + exp.togmtstring () + ";p ath=/"; else {var keyvalue = GetCookie (name, key); if (KeyValue!= "") {Namevalue = Namevalue.replace (key + "=" + KeyValue, ke Y + "=" +encodeuri (value)); Document.cookie = name + "=" + Namevalue + "; expires=" + exp.togmtstring () + ";p ath=/"; else {document.cookie = name + "=" + Namevalue + "&" + key + "=" + encodeURI (value) + "; expires=" + exp.togmtstring () + ";p ath=/"; Read the Cookies function GetCookie (name,key) {var namevalue = ""; var arr,reg=new RegExp ("(^|)" +name+ "= ([^;] *)(;|$)"); if (arr = Document.cookie.match (reg)) { Namevalue = decodeURI (arr[2]); } if (key!= null && key!= "") {reg = new RegExp ("(^| |&)" + key + "= ([^ (; |&|=)]*) (&|$)"); if (arr = Namevalue.match (reg)) {alert (decodeURI (arr[2)); return decodeURI (Arr[2]);} else return "";} else {return namevalue;}} Delete Cookies function Delcookie (name) {var exp = new Date (); Exp.settime (Exp.gettime ()-1); var cval = GetCookie (name); F (cval!= null) Document.cookie = name + "=" + Cval + "; expires=" + exp.togmtstring (); }
ASP. NET Server-side Action cookie Code (sample):
protected void Showcookiebutton_click (object sender, EventArgs e) {string name = this. Nameservertextbox.text; String key = this. Keyservertextbox.text; if (Request.cookies[name]!= null && request.cookies [name][key]!=null) {This.showCookieServerTextBox.Text = Server.urldecode (Request.cookies[name][key]); } protected void Setcookieserverbutton_click (object sender, EventArgs e) {string name = this. Nameservertextbox.text; String key = this. Keyservertextbox.text; HttpCookie HttpCookie; if (request.cookies[name] = = null) {HttpCookie = new HttpCookie (name); Httpcookie.path = "/"; httpcookie.expires = Dateti Me. Now.adddays (2); if (key. Trim ()!=string. Empty) Httpcookie[key] =server.urlencode (this.setCookieServerTextBox.Text); else Httpcookie.value = Server.URLEncode (This.setCookieServerTextBox.Text); RESPONSE.COOKIES.ADD (HttpCookie); else {try {HttpCookie = Request.cookies[name]; if (key). Trim () = = string. Empty) Httpcookie.value = Server.URLEncode (THIS.SETCOOKIESERVERTEXTBOx. Text); else Httpcookie[key] = Server.URLEncode (This.setCookieServerTextBox.Text); Httpcookie.expires = DateTime.Now.AddDays (2); Httpcookie.path = "/"; RESPONSE.COOKIES.ADD (HttpCookie); This method in the annotation only assigns a value to the cookie value of the Name-key, and if there are other subkeys under name, the values of the other subkeys are lost//if (key). Trim () = = "")//Response.cookies[name]. Value = Server.URLEncode (This.setCookieServerTextBox.Text); else//Response.cookies[name][key] = Server.URLEncode (This.setCookieServerTextBox.Text); Response.cookies[name]. Expires = DateTime.Now.AddDays (2); Response.cookies[name]. Path = "/"; catch (Exception EP) {}}}
It is important to note that the cookie's Path attribute must be set path= "/" at the client and server side, so that the operation of JS and ASP.net can interact with the cookie. Another is the problem of coding, where the encoding in JS is encodeuri corresponding to the ASP.net server.urlencode.
The main reason is that the default definition of path is not the same for both parties
The problem is actually due to a conflict in domain and path names into my cookie. The. NET control, apparently by default, built my cookie using the domain name and the root path. JavaScript, apparently by default, built my cookies using the domain name and full path.
We only need to set the same path= "/" Can