ASP. NET Cookie and session

Source: Internet
Author: User
Tags httpcontext setcookie

Cookies and sessionc# on the server, JS in client client authentication is not a substitute for service-side validationHttp

HTTP belongs to the application layer, the HTTP protocol has five major features: 1, support client/server mode, 2, simple and fast, 3, flexible, 4, no connection, 5, stateless.

No status

Stateless means that the protocol has no memory capacity for transactional processing. A lack of state means that if the previous information is required for subsequent processing, it must be re-routed, which may cause the amount of data to be transferred per connection to increase. On the other hand, it responds faster when the server does not need the previous information.

The HTTP protocol is stateless and will not remember the last time and the page "what happened".

The HTTP protocol is a stateless protocol. Once the data has been exchanged, the client-to-server connection is closed, and exchanging the data again requires establishing a new connection. This means that the server is unable to track the session from the connection .

The server does not remember the last time it gave the browser what, otherwise the server pressure will be too large. Each time the request arrives at ASP, a new object of HttpHandler is created to handle.
1         intI//put it outside and put it in the main function, i++ will not initialize2         //each time a request is requested, a new object will be3          Public voidProcessRequest (HttpContext context)4         {5             6Context. Response.ContentType ="text/html";7             stringPath = HttpContext.Current.Server.MapPath ("~/htmlpage1.html");8             stringstr =file.readalltext (path);9             stringhtml;Ten             if(string. IsNullOrEmpty (context. request["TJ"])) One             { Ahtml = str. Replace ("@qq","0"); -i =2; -             } the             Else -             { -i++;//int Default value is 0, Output 1, no output 2 -html = str. Replace ("@qq", i.ToString ()); +             } -Context. Response.Write (HTML);

The browser needs to remember these values, the next time you submit the server will be the last time to submit the value to the server, let him think up. If you want to know the last state, one method is to save the state information to the page form before the end of the browser response, and the next time the page makes a request to the server, the server will be able to restore the last state based on the status information.

No connection

The meaning of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives the customer's answer, the connection is disconnected. In this way, the transmission time can be saved.

Two techniques for keeping the HTTP connection state come into being: a Cookie and a session.

Session tracking is a common technique used in Web programs to track a user's entire session . Common session tracking techniques are cookies and sessions. The cookie determines the user's identity by logging information on the client , and thesession determines the user's identity by logging information on the server side .


A cookie is a solution that maintains state through the client.

In the program, session tracking is a very important thing. In theory, all request actions for one user should belong to the same session , while all request actions for another user should belong to another session

give the client a pass, one per person, who must carry his or her pass. This allows the server to confirm the identity of the client from the pass. That's how cookies work .

A cookie is actually a small piece of text information. The client requests the server and, if the server needs to log the user state, uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the site again, the browser submits the requested URL along with the cookie to the server. The server checks the cookie to identify the user state. The server can also modify the contents of the cookie as needed.

Cookies are site-related and each time a request is made to the server, all cookies associated with the site are submitted to the server in addition to the form parameters. The cookie is also stored on the browser side, and the browser submits the cookie associated with the site to the server each time it is requested, and the cookie returned by the server is updated back to the database, so that the information can be stored in a cookie and then read, Modified (read the paper). Cookies can keep the login information to the user's next session with the server, in other words, the next time you visit the same website, the user will find that you do not have to enter a user name and password to log in (of course, do not exclude the user manually delete cookies). There are also some cookies that are deleted when the user exits the session, which can effectively protect the privacy of the individual.
 1  context. Response.ContentType =   " ;  2  co Okie: Key-value pairs  3  HttpCookie cookie1 = context. Request.cookies[  " ";  4  5  context. Response.Write (Cookie1==null ?   No test this cookie  : Cookie1. Value); 
If the expires is not set then the life cycle is closed and the browser terminates, otherwise "up" to expires. "Save 7 Days".
1Context. Response.ContentType ="text/html";2HttpCookie cookie =NewHttpCookie ("Test");3             //cookies. Value = "";4Cookies. Value =context. request.useragent;5             /*6 cookies. Expires = DateTime.Now.AddDays;// Current Time7 //datetime's adddays is the addition of 20 days on this datetime basis, returning a new DateTime object*/8             //cookies. Expires = DateTime.Now.AddSeconds (ten);9             //If the expires time-out is not set, the cookie expires after you close the browserTen             //If you set the expires, the browser is opened again, even if you close the browser , and you can read OneCookies. Expires = DateTime.Now.AddMinutes (5);//AddDays (+) AContext. Response.setcookie (cookie);

Different browser cookies are independent.

A cookie is a store of information in an HTTP message header.

The disadvantage of cookies: it is not possible to store too much information, confidential information can not be stored (do not want users to see or can not be altered by the user to put the information into the cookie). Cookies: They can be erased, cannot be stored in a cookie that cannot be lost, and may have expired without expires.

Cookies cannot be read and written across domain names.

Problem with path when writing cookie: path is empty, both the current path and the subfolder can be read.
1Context. Response.ContentType ="Text/plain";2HttpCookie Lastcookie = context. request.cookies["C1"];3Context. Response.Write (lastcookie==NULL?"No Cookies": lastcookie.value);4 5 6HttpCookie cookie =NewHttpCookie ("C1");7Cookies. Value ="";8Cookies. Domain =".";// vip.rupeng.com9             //The default of path is "/" and all pages under the current domain name can manipulate this cookieTenCookies. Path ="/day4/cookiepath1.ashx";//Path: Who can read Me OneContext. Response.setcookie (cookie);

Set all properties of a cookie

In addition to name and value, cookies have several other commonly used properties. Each property corresponds to a getter method with a setter method. All the properties of the cookie class are shown in Table 1.1.

Table 1.1 Cookie Common Properties

Property name


String Name

The name of the cookie. Once a cookie is created, the name cannot be changed

Object value

The value of the cookie. If the value is a Unicode character, the character encoding is required. If the value is binary data, you need to use BASE64 encoding

int MaxAge

The time, in seconds, that the cookie expires. If positive, the cookie expires after maxage seconds. If it is a negative number, the cookie is a temporary cookie and the browser is deactivated and the browser does not save the cookie in any way. If 0, the cookie is deleted. The default is –1

Boolean secure

Whether the cookie is only transmitted using security protocols. Security protocols. The security protocol has HTTPS,SSL, and so on, before transmitting data on the network to encrypt the data first. Default is False

String Path

The path to use for the cookie. If set to "/sessionweb/", only programs with ContextPath "/sessionweb" can access the cookie. If set to "/", the cookie can be accessed by ContextPath under this domain name. Note that the last character must be "/"

String Domain

The domain name in which the cookie can be accessed. If set to ".", all domain names ending with "" can access the cookie. Note the first character must be "."

String Comment

A description of the use of the cookie. This description is displayed when the browser displays cookie information

int version

The version number used by the cookie. 0 indicates compliance with the cookie specification of Netscape, 1 is the RFC 2109 specification followed by the consortium

Modification and deletion of cookies

Cookies do not provide modifications or deletions. If you want to modify a cookie, simply create a new cookie with the same name and add it to the response to overwrite the original cookie.

If you want to delete a cookie, simply create a new cookie with the same name and set MaxAge to 0 and add it to response to overwrite the original cookie. Note that it is 0, not a negative number. Negative numbers represent other meanings.

When you modify or delete a cookie, all properties except value and MaxAge, such as name, path, domain, and so on, are identical to the original cookie. Otherwise, the browser will be treated as two different cookies without overwriting, causing the modification and deletion to fail.

Security attributes for Cookies

The HTTP protocol is not only stateless, but also unsafe. Data that uses the HTTP protocol is transmitted directly over the network without any encryption, and there is the possibility of interception. Using the HTTP protocol to transmit very confidential content is a hidden danger. If you do not want cookies to be transmitted in non-secure protocols such as HTTP, you can set the cookie's secure property to true. The browser will only transmit such cookies in security protocols such as HTTPS and SSL. The following code sets the secure property to true:

1 New Cookie ("Time""20080808"//  new Cookie  2 cookie.setsecure (true);                           // Setting security Properties 3 Response.addcookie (cookie);                        // Output to client

JavaScript Action Cookie

Cookies are stored on the browser side, so the browser has a prerequisite for manipulating cookies. Browsers can manipulate cookies using scripting programs such as JavaScript or VBScript. Here is a JavaScript example that describes common cookie operations. For example, the following code will output all cookies on this page.

1 <script>document.write (document.cookie);</script>

Because JavaScript is able to read and write cookies arbitrarily, some good people want to use JavaScript programs to spy on users ' cookies on other websites. In vain, however, the organization has long recognized the security implications and preparedness of JavaScript to read and write cookies, and the standard browser will prevent JavaScript from reading and writing any cookies that are not part of its own web site. In other words, a Web site's JavaScript program reads and writes the cookie for the B site without any results.


Sessions, also known as session state, are the most commonly used state in a web system to maintain some information related to the current browser instance. We often use the session to store the user state in order to control user access.

A session is a mechanism for recording the state of a customer, unlike a cookie that is stored in a client browser and the session is stored on the server. When the client browser accesses the server, the server logs the client information to the server in some way. This is the session. When the client browser accesses it again, it only needs to find the customer's status from that session.

If the cookie mechanism is to determine the customer's identity by checking the "pass" on the client, then the session mechanism verifies the customer's identity by checking the "customer schedule" on the server. Session is equivalent to a program on the server set up a customer profile, when customers visit only need to query the customer file table on it.

the life cycle of the session

Session is saved on the server side. In order to obtain higher access speed, the server usually puts the session in memory. Each user will have a separate session. If the session content is too complex, a large number of clients accessing the server can cause memory overflow. Therefore, the information in the session should be as concise as possible.

after the session is generated, the server updates the last access time of the session and maintains the session as long as the user continues to accessit. Each time a user accesses a server, the server considers the user's session "active" once, regardless of whether the session is read or written.

duration of Session

As more and more users access the server, the session will be more and more. to prevent memory overflow, the server removes the session from memory that has not been active for a long period of time. This is the time-out period of the session. If you have exceeded the time-out period and have not accessed the server, the session will automatically expire.

Common methods of Session

The session includes a variety of methods that are much more convenient to use than cookies. The common methods of the session are shown in table 1.2.

Table 1.2 Common methods of HttpSession

Method name


void SetAttribute (String attribute, Object value)

Sets the session property. The value parameter can be any Java Object. Typically a Java Bean. Value information should not be too large

String getattribute (String attribute)

Return to session Properties

Enumeration Getattributenames ()

Returns the name of a property that exists in the session

void RemoveAttribute (String attribute)

Remove Session Properties

String GetId ()

Returns the ID of the session. The ID is automatically created by the server and is not duplicated

Long GetCreationTime ()

Returns the date the session was created. The return type is long and is often converted to a date type, for example: Date Createtime = new Date (Session.get creationtime ())

Long Getlastaccessedtime ()

Returns the last active time of the session. return type is long

int Getmaxinactiveinterval ()

Returns the time-out period for the session. Unit is seconds. There is no access at this time, the server considers the session to be invalid

void Setmaxinactiveinterval (int second)

Sets the time-out period for the session. Unit is seconds

void Putvalue (String attribute, Object value)

The deprecated method. has been replaced by setattribute (String attribute, Object Value)

Object getValue (String attribute)

Methods that are not recommended. has been replaced by getattribute (String attr)

Boolean isnew ()

Returns whether the session is a newly created

void Invalidate ()

Invalidate the session

The default time-out for the session in Tomcat is 20 minutes. The time-out is modified by setmaxinactiveinterval (int seconds). You can modify Web. XML to change the session's default timeout time. For example, modify to 60 minutes:


<session-timeout>60</session-timeout> <!--units: minutes--


Note The:<session-timeout> parameter is in minutes, and setmaxinactiveinterval (int s) is the second unit.

Use session to implement redirection:
1    Public Const stringLoginurl ="loginurl";//the address of the page when trying to log in2 //=========================================================================================================== ==//3  if(Username = =NULL)//redirect to landing page if not logged in4             {5Context. Session[login.loginurl] = context. Request.Url.ToString ();//Save the current address in the session6Context. Response.Redirect ("login.ashx");7}

ASP. NET Cookie and session

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: 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.