Cookie interoperability between ASP. Net and JS

Source: Internet
Author: User
Tags in domain
Cookie interoperability between ASP. Net and JS

Recently, the Cookie problem has been around for several days. Due to project requirements, both the client and the server have to perform Cookie operations, and the server-side cookies both carry sub-keys. Previously, they were read by the client, the code for setting and deleting cookies (lazy) is implemented by google and is in the name = value format without subkeys. Therefore, before the Cookie is completely clarified, I made a few changes to the copied code and used it to my website. At last, I was very depressed. For several days, I had a problem reading and writing cookies, I have consolidated my Cookie knowledge to find out why!
First, let's look at the following Cookie concise reference: (from: http://www.builder.com.cn/2007/1024/576287.shtml)
1. Write Cookie
1. the Name and Value attributes are set by the program. The default values are empty references.
2. The default value of the Domain attribute is the Domain name of the current URL, regardless of the directory of the page where the cookie is sent.
For example, http://www.cnblogs.com/bmwchampion/archive/2009/08/31/aspnet_js_cookie.html? Opt = 1 page sends a cookie, Domain property default is http://www.cnblogs.com/bmwchampion/archive/2009/08/31/aspnet_js_cookie.html? Opt = 1, which can be set as required by the program.
3. The default value of the Path attribute is the root directory, that is, "/", regardless of the directory of the page where the cookie is sent. The program can be set to a certain path to further limit the scope of the cookie.
4. Expires attribute, which sets the Cookie expiration date and time. If you do not set the Cookie validity period (the default setting), you can also create a Cookie, but it will not be saved to the user's hard disk, but will become part of the user's session information, when the browser is closed or the session times out, the Cookie disappears. This Cookie is called a non-permanent Cookie. The Cookie for storing SessionID is such a Cookie, which is not stored on the hard disk and only exists in the memory.
5. The Cookie to be sent can be sent to the client by attaching it to the Cookie attribute of Response: Reponse. Cookies. Add (Cookie)
6. All cookies with the same Domain attribute and Path attribute exist in a file on the client. The cookies are separated. The first line of each Cookie is the name of the Cookie, the second line is the value, and the third line is a string consisting of the Domain Attribute + Path attribute, indicating the scope of the Cookie, the other rows contain the daily processing information of cookies, such as the expiration date and time. There is also a simple checksum in the Cookie. If you change the length of the Cookie name or value, the browser will detect the modification and delete the Cookie.
2. Read Cookie
1. The Request. Cookie attribute contains a set of all Cookies sent from the client to the server. Only Cookies within the scope of the Request URL will be sent to the server by the browser along with the Http Request.
2. The attributes of Name and Value and the values of subkeys are easy to read.
3. the Domain and Path attributes cannot be read, The read Domain attribute is always "", and the read Path attribute is always "/". These attributes have limited usage. If your page and Cookie are not in the same domain, you will not receive the Cookie at the page location.
4. The Cookie expiration date and time cannot be read. In fact, when the browser sends Cookie information to the server, the browser does not include the expired information. You can read the Expires attribute, but always return a zero date/time value. The Expires attribute is mainly used to help the browser perform daily management of Cookie storage. From the server perspective, the Cookie either exists or does not exist. Therefore, the validity period is not useful for the server.
Therefore, the browser does not provide this information when sending cookies. If you need the Cookie expiration date, you must reset it.
3. Modify and delete cookies
1. In fact, you cannot directly modify a Cookie by creating a Cookie with the same name and sending the Cookie to the browser to overwrite the old Cookie on the client.
2. similarly, you cannot directly delete a Cookie. You can modify a Cookie to allow the browser to help you delete the Cookie. Modify the Cookie's validity period to a certain time in the past, when the browser checks the Cookie validity period, the expired Cookie is deleted.
Relationship between Cookie and Session
1. session in asp.net can adopt cookie and cookieless methods. cookieless places SessionID in the URL and transmits it back and forth between the client and the server without cookie. This method is not discussed here.
2. In asp.net, when the customer requests a URL for the first time, the server generates a SessionID for the customer and sends it to the client using a non-permanent Cookie.
3. Non-permanent cookies disappear only when the browser is closed. The Session timeout is determined as follows:
3.1 When the client accesses the server for the first time, it will get a SessionID and send it to the client as a non-permanent Cookie.
3.2 When you access this URL before closing the browser, the browser will send this SessionID to the server, the server maintains various statuses of the server corresponding to this customer based on the SessionID (that is, various values saved in the Session) and can operate on these sessions in the web application.
3.3 The server maintains the expiration time of this SessionID. You can set the Session Timeout time in IIS. Each request causes the server to extend the expiration time of this SessioID by a set timeout time.
3.4 when the server finds that a SessionID is out of date, that is, a customer has not accessed the site again within the specified timeout period, and deletes the SessionID along with all Session variables related to the SessionID.
3.5 before the browser of the client is closed, the server does not know that the SessionID has been deleted. The client still sends the cookie of this SessionID to the server, but the server does not know the SessionID at this time, the user is treated as a new user and a new SessionID is assigned again.
Then I paste the code for adding, deleting, and modifying cookies on the client and the Code for adding, deleting, and modifying cookies on the server:

Add, delete, and modify cookies in js:
// JS cookies operation method!
// Write cookies
Function setCookie (value, name, key ){
Var Days = 2;
Var exp = new Date ();
Exp. setTime (exp. getTime () + Days x 24x60*60*1000 );
If (key = null | key = ""){
Document. cookie = name + "=" + encodeURI (value) + "; expires =" + exp. toGMTString () + "; path = /";
}
Else {
Var nameValue = getCookie (name );
If (nameValue = ""){
Document. cookie = name + "=" + key + "=" + encodeURI (value) + "; expires =" + exp. toGMTString () + "; path = /";
}
Else {
Var keyValue = getCookie (name, key );
If (keyValue! = ""){
NameValue = nameValue. replace (key + "=" + keyValue, key + "=" + encodeURI (value ));
Document. cookie = name + "=" + nameValue + "; expires =" + exp. toGMTString () + "; path = /";
}
Else {
Document. cookie = name + "=" + nameValue + "&" + key + "=" + encodeURI (value) + "; expires =" + exp. toGMTString () + "; path = /";
}
}
}
}
// Read 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 );
If (cval! = Null) document. cookie = name + "=" + cval + "; expires =" + exp. toGMTString ();
}
Code for Cookie operation on ASP. NET Server Side (example ):
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 = DateTime. 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 values to the cookie value corresponding to name-key. If there are other subkeys under name, the values of 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)
{
}

}
}
// Code ended
Note that you must set the Path = "/" attribute on both the client and server to interact with the Cookie operations of js and ASP. NET! Another issue is encoding. Here, the encoding in JS is encodeURI, which corresponds to Server. URLEncode of ASP. NET.
The main reason is that the default value of Path is different between the two parties.

The problem was actually due to a conflict in domain and path names in 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 cookie using the domain name and FULL path.
We only need to set the same Path = "/".

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.