Read examples of cookies in C #

Source: Internet
Author: User
Tags setcookie

Reading of cookies in C #

Link:

First, write a 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 the directory in which the page that issued the cookie is placed.

The Domain property defaults to www.kent.com, which can be set by the program to the desired value.

3. The default value of the Path property is the root directory, or "/", regardless of the directory in which the page that issued the cookie is placed. You can further limit the scope of this cookie by setting the program to a certain path.

4. Expires property, this property sets the expiration date and time of this cookie. If you do not set a cookie's expiration date (the default setting), you can also create a cookie, but it will not be saved to the user's hard disk, but may 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 a cookie that is not stored on the hard disk and is only in memory.

5. This cookie can be sent to the client by attaching the cookie that is to be issued to the response's Cookie attribute: Reponse.Cookies.Add (Cookie)

6. All cookies with the same domain property +path property have a file in the client, and the cookie is split "*" between the cookies. The first line of each cookie is the name of the cookie, the second line is the value, the third line is a string of the Domain property +path property, indicates the scope of the cookie, and the remaining rows contain 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 length of the cookie name or value, the browser detects that the cookie is modified and deleted.

Second, read the cookie

1. The Request.Cookies property contains a collection of all the cookies sent to the server by the client, and only cookies that are within the scope of the request URL are sent to the server along with the HTTP request.

2. The Name and Value properties and subkey values are easily readable.

3. The domain and path properties are not readable, the Read domain property is always "", and the Read Path property is always "/". The use of these attributes was limited. If your page and Cookie are not in the same domain, you will not receive the cookie at all in the location of the page.

4. The expiration date and time of the cookie cannot be read either. In fact, when the browser sends cookie information to the server, the browser does not include the expiration information. You can read the Expires property, but always return a date/time value of zero. The primary function of the Expires property is to help the browser perform the daily management of Cookie preservation. From the server's point of view, the Cookie either exists or does not exist, so the expiration date is not a useful information for the server. Therefore, the browser does not provide this information when sending a Cookie. If you need a Cookie expiration date, you must reset it.

Third, modify and delete cookies

1. You cannot directly modify a cookie by creating a cookie with the same name and sending the cookie to the browser, overwriting 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 remove the cookie for the purpose of modifying the cookie is valid for a certain time in the past, when the browser checks the validity of the cookie, it will delete the expired Cookies. Modify Validity Period Delete Cookie

Iv. the relationship between the cookie and the session

1. The session in ASP. NET can adopt the cookie and cookieless two methods, cookieless way is to put SessionID in the URL in the client and the server to pass back and forth, do not need to use the cookie, here does not discuss this way.

2. In ASP. For the first time the customer requests a URL, the server generates a SessionID for the client and sends it to the client with a non-persistent cookie.

3. Non-persistent cookies only disappear after the browser is closed, and the session's timeout is determined as a process:

3.1 For the first time, the client Access server will get a sessionid that is sent to the client with a non-persistent cookie.

3.2 Before this browser is closed to access this URL, the browser will send this sessionid to the server, the service side according to SessionID to maintain the client's service side of the various states (is the session of the various values saved), These sessions can be manipulated in a Web application.

3.3 The server side maintains the expiration time of this SessionID, and IIS can set the session timeout. Each request will cause the server to extend the expiration time of this sessioid by a set time-out.

3.4 When the server discovers that a sessionid is outdated, that a customer has not visited the site again within the set timeout period, this sessionid, along with all session variables related to this SessionID, is deleted.

3.5 The client's browser does not close before, do not know that the server has already deleted this SessionID, the client still send this SessionID cookie to the server, but at this time the service side has not known this sessionid, will this user as a new user, Assign a new SessionID again.

Creation of cookies:

Create a username cookie on the client with a value of GJY, valid for 1 days.

Method 1:

response.cookies["username"]. Value= "ZXF"; response.cookies["username"]. Expires=datetime.now.adddays (1);

Method 2:

System.Web.HttpCookie newcookie=new HttpCookie ("username"); Newcookie. Value= "Gjy"; Newcookie. Expires=datetime.now.adddays (1); Response.appendcookie (Newcookie);

Create cookies with sub-keys:

System.Web.HttpCookie newcookie=new HttpCookie ("user"); Newcookie. values["username"]= "zxf"; Newcookie. values["Password"]= "111"; Newcookie. Expires=datetime.now.adddays (1); Response.appendcookie (Newcookie);

Or:

SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Cookie);

Cookies are read:

No Child key reads:

if (request.cookies["username"]!=null) {Response.Write (Server.urldecode (request.cookies["username"]));

Or:

Httpcontext.current.request.cookies[strcookiename]}

There are child keys to read:

if (request.cookies["user"]!=null) {Response.Write (Server.urldecode (request.cookies["user"] ["username"]. Value)); Response.Write (Server.urldecode (request.cookies["user"] ["password"]. Value));

Two ways to add and read:

Add to:

Response.appendcookie (Newcookie); SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Cookie);

Read:

request.cookies["username"]httpcontext.current.request.cookies["username"]

Cookies automatically expire when the browser is closed, as long as the cookie is not set to expire

Delete Cookie modification time: cookie.expires = DateTime.Now.AddDays ( -1);

Using system;using system.data;using system.configuration;using system.web;using system.web.security;using System.web.ui;using system.web.ui.webcontrols;using system.web.ui.webcontrols.webparts;using System.Web.UI.HtmlControls; public class cookie{//<summary>///cookies//</summary>//<param name= "StrName" > Primary key    </param>//<param name= "strvalue" > Key value </param>//<param name= "Strday" > Active days </param> <returns></returns> public bool Setcookie (string strName, string strvalue, int strday) {TR            y {HttpCookie Cookie = new HttpCookie (strName); Cookie.domain = ". xxx.com"; When you want to cross-domain access, specify the domain name for the Cookie, in the format. xxx.com cookie.expires = DateTime.Now.AddDays (Strda            y);            Cookie.value = strvalue;            SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Cookie);        return true;        } catch {return false; }    }   <summary>///Read cookies///</summary>//<param name= "StrName" > Primary key </param>// <returns></returns> public string GetCookie (string strName) {HttpCookie Cookie = System.Web.Ht        Tpcontext.current.request.cookies[strname];        if (Cookie = null) {return Cookie.Value.ToString ();        } else {return null;     }}///<summary>//delete cookies//</summary>//<param name= "StrName" > Primary key </param> <returns></returns> public bool Delcookie (string strName) {try {Httpc            Ookie Cookie = new HttpCookie (strName);            Cookie.domain = ". xxx.com"; When you want to cross-domain access, specify the domain name for the Cookie, in the format. xxx.com cookie.expires = DateTime.Now.AddDays (-1);            SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Cookie);        return true;    } catch {return false;    }    }} 


Example:

Cookie cookie = new Cookie (); Cookie.setcookie ("name", "AAA", 1);//Assignment Cookie.getcookie ("name");//value Cookie.delcookie ("name");//delete
Using system;using system.data;using system.configuration;using system.web;using system.web.security;using System.web.ui;using system.web.ui.webcontrols;using system.web.ui.webcontrols.webparts;using System.Web.UI.HtmlControls; public class cookie{//<summary>///cookies//</summary>//<param name= "StrName" > Primary key    </param>//<param name= "strvalue" > Key value </param>//<param name= "Strday" > Active days </param> <returns></returns> public bool Setcookie (string strName, string strvalue, int strday) {TR            y {HttpCookie Cookie = new HttpCookie (strName); Cookie.domain = ". xxx.com"; When you want to cross-domain access, specify the domain name for the Cookie, in the format. xxx.com cookie.expires = DateTime.Now.AddDays (Strda            y);            Cookie.value = strvalue;            SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Cookie);        return true;        } catch {return false; }    }   <summary>///Read cookies///</summary>//<param name= "StrName" > Primary key </param>// <returns></returns> public string GetCookie (string strName) {HttpCookie Cookie = System.Web.Ht        Tpcontext.current.request.cookies[strname];        if (Cookie = null) {return Cookie.Value.ToString ();        } else {return null;     }}///<summary>//delete cookies//</summary>//<param name= "StrName" > Primary key </param> <returns></returns> public bool Delcookie (string strName) {try {Httpc            Ookie Cookie = new HttpCookie (strName);            Cookie.domain = ". xxx.com"; When you want to cross-domain access, specify the domain name for the Cookie, in the format. xxx.com cookie.expires = DateTime.Now.AddDays (-1);            SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Cookie);        return true;    } catch {return false;    }    }} 

Example:

Cookie cookie = new Cookie (); Cookie.setcookie ("name", "AAA", 1);//Assignment Cookie.getcookie ("name");//value Cookie.delcookie ("name");//delete

Note: When a cookie is garbled in Chinese, it is encoded in Chinese when it is stored, such as Cookie.setcookie("name", "Server"). UrlEncode ("AAA"), 1), decoding when read

Also: Cookies automatically expire when the browser is closed, as long as the cookie is not set to expire

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.