Partager via


Using Cookies to Maintain Sessions in ASP

A cookie is a token that the Web server embeds in a user's Web browser to identify the user. The next time the same browser requests a page, it sends the cookie it received from the Web server. Cookies allow a set of information to be associated with a user. ASP scripts can both get and set the values of cookies by using the Response.Cookies Collection collection of the Response and Request objects.

About SessionID and Cookies

The first time a user requests an .asp file within a given application, ASP generates a SessionID. A number produced by a complex algorithm, the SessionID uniquely identifies each user's session. At the beginning of a new session, the server stores the Session ID in the user's Web browser as a cookie.

The SessionID cookie is similar to a locker key in that, as the user interacts with an application during a session, ASP can store information for the user in a "locker" on the server. The user's SessionID cookie, transmitted in the HTTP request header, enables access to this information in the way that a locker key enables access to a locker's contents. Each time that ASP receives a request for a page, it checks the HTTP request header for a SessionID cookie.

After storing the SessionID cookie in the user's browser, ASP reuses the same cookie to track the session, even if the user requests another .asp file, or requests an .asp file running in other application. Likewise, if the user deliberately abandons or lets the session timeout, and then proceeds to request another .asp file, ASP begins a new session using the same cookie. The only time a user receives a new SessionID cookie is when the server administrator restarts the server, thus clearing the SessionID settings stored in memory, or the user restarts the Web browser.

By reusing the SessionID cookie, ASP minimizes the number of cookies sent to the browser. Additionally, if you determine that your ASP application does not require session management, you can prevent ASP from tracking session and sending SessionID cookies to users.

ASP will not send the session cookies under the following conditions:

  • If an application has session state disabled.

  • If an ASP page is defined as sessionless, that is, a page containing the

    <%@ EnableSessionState=False %>
    

    tag. For more information, see Sessionless ASP Pages.

You should also note that SessionID cookies are not intended to provide a permanent or secure means for tracking users across multiple visits to a Web site. The SessionID information stored in the server computer's memory can be easily lost or impersonated by a malicious user. If you want track users who visit your Web application over a longer periods, you must create a user identification by storing a special cookie in a user's Web browser and saving the cookie information to a database. If you do so, configure your application to use SSL in order to encrypt the SessionID and protect it from malicious users. For more information, see Using Cookies and see "Secure Sockets Layer" in IIS Help, which is accessible from IIS Manager..

Setting Cookies

To set the value of a cookie, use Response.Cookies. If the cookie does not already exist, Response.Cookies creates a new one. For example, to send a cookie named ("VisitorID") with an associated value ("49") to the browser, use the following command, which must appear on your Web page before the <HTML> tag:

<% Response.Cookies("VisitorID") = 49 %> 

If you want a cookie to be used only during the current user session, then sending the cookie to the browser is all you need to do. However, if you want to identify a user even after the user has stopped and restarted the browser, you must force the browser to store the cookie in a file on the client computer's hard disk. To save the cookie, use the Expires attribute for Response.Cookies and set the date to some date in the future:

<% 
  Response.Cookies("VisitorID") = 49  
  Response.Cookies("VisitorID").Expires = "December 31, 2001"  
%> 

A cookie can have multiple values; such a cookie is called an indexed cookie. An indexed cookie value is assigned a key; you can set a particular cookie key value. For example:

<% Response.Cookies("VisitorID")("49") = "Travel" %> 

If an existing cookie has key values but Response.Cookies does not specify a key name, then the existing key values are deleted. Similarly, if an existing cookie does not have key values but Response.Cookies specifies key names and values, the existing value of the cookie is deleted and new key-value pairs are created.

Getting Cookies

To get the value of a cookie, use the Request.Cookies collection. For example, if the user HTTP request sets

VisitorID=49

, then the following statement retrieves the value

49

:

<%= Request.Cookies("VisitorID") %> 

Similarly, to retrieve a key value from an indexed cookie, use the key name. For example, if a user's browser sends the following information in the HTTP request header:

Cookie: VisitorID=49=Travel 

The following statement would then return the value

Travel

:

<%= Request.Cookies("VisitorID")("49") %> 

Each cookie stored by ASP on the user's Web browser contains path information. When the browser requests a file stored in the same location as the path specified in the cookie, the browser automatically forwards the cookie to the server. By default, cookie paths correspond to the name of the application containing the .asp file that originally generated the cookie. For example, if an .asp file, residing in an application called UserApplication, generates a cookie, then each time a user's Web browser retrieves any file residing in that application, the browser will forward the cookie, in addition to any other cookies containing the path /UserApplication.

To specify a path for a cookie other than the default application path, you can use the ASP Response.Cookies collection's Path attribute. For example, the following script assigns the path SalesApp/Customer/Profiles/ to a cookie called

Purchases

:

<% 
  Response.Cookies("Purchases") = "12"  
  Response.Cookies("Purchases").Expires = "January 1, 2001"  
  Response.Cookies("Purchases").Path = "/SalesApp/Customer/Profiles/" 
%> 

Whenever the Web browser containing the

Purchases

cookie requests a file residing in the path /SalesApp/Customer/Profiles/ or in any of it subdirectories, the browser forwards the cookie to the server.

Many Web browsers, including Microsoft Internet Explorer version 4.0, or later, and Netscape browsers, preserve the case of the cookie path. This means that if the case of the path of a requested file differs from the case of the stored cookie path, the browser will not send the cookie to the server. For example, to ASP, the virtual directories /TRAVEL and /travel are the same ASP application, but to a browser that preserves the case of a URL, /TRAVEL and /travel are two different applications. Make sure all URLs to .asp files have the same case to ensure that the user's browser forwards stored cookies.

You can use the following statement to set the cookie path so that the user's Web browser will forward a cookie whenever the browser requests a file from your server, regardless of application or path:

Response.Cookies("Purchases").Path = "/" 

Note, however, that forwarding cookies to the server, without distinguishing between applications, raises a potential security concern if the cookies contain sensitive information that should not be accessible outside of a specific application.

Preserving State without Cookies

Not all browsers support cookies. Even with browsers that do support cookies, some users prefer to turn off cookie support. If your application needs to be responsive to browsers that don't support cookies, you cannot use ASP session management.

In this case, you must write your own mechanism to pass information from page to page in your application. There are two general ways to do this:

  • Add parameters to a URL's query string. For example:

    http://MyServer/MyApp/start.asp?name=Jeff 
    

    Some browsers, however, will discard any explicit parameters passed in a query string if a form is submitted with the GET method.

  • Add hidden values to a form. For example, the following HTML form contains a hidden control, which does not appear on the actual form and remains invisible in the user's Web browser. The form passes a user identification value, in addition to the information supplied by the user, by using the HTTP POST method.

    <FORM METHOD="POST" ACTION="/scripts/inform.asp"> 
    <INPUT TYPE="text" NAME="city" VALUE=""> 
    <INPUT TYPE="text" NAME="country_region" VALUE =""> 
    <INPUT TYPE="hidden" NAME="userid" VALUE= <%= UserIDNum(i) %> 
    <INPUT TYPE="submit"  VALUE="Enter"> 
    

    This method requires all link destinations that pass user information to be coded as HTML forms.

If you are not using ASP session management, you should turn off session support for your application. When sessions are enabled, ASP sends a SessionID cookie to each browser that requests a page. To turn off session support, clear the Enable Session State check box on the Application Options property sheet in the Internet Information Services snap-in.