session usage and expiration Judgment Program

Source: Internet
Author: User
Tags server memory

1. Session is one of the common states in Web sessions.

2. Session provides a way to store information in the server memory. It can store any data type, including custom objects.

3. The Seesion of each client is stored independently.

4. The Session information will be saved as long as the cookie of the SessionID is not lost throughout the Session.

5. The Session cannot be accessed across processes and can only be accessed by the user of the Session. The id used to extract Session data should be saved to the cache of the visitor's browser as a Cookie.

6. When the Session ends or expires, the server clears the Session object.

7. Session is often used to save the login user ID.

8. The data stored by the Session is Global across pages.

For example, if we want to know how many pages a user visits our website browses, we may add the following to each page that a user may access:

The code is as follows: Copy code
If Session ("PageViewed") = "" Then
Session ("PageViewed") = 1
Session ("PageViewed") = Session ("PageViewed") + 1
End If

You can use the following sentence to learn about several pages you have browsed:

The code is as follows: Copy code

Response. Write ("You have viewed" & Session ("PageViewed") & "pages ")

Session usage

The code is as follows: Copy code

<Head runat = "server">
<Title> </title>
<Script src = "Scripts/jquery-1.4.1.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Function getSessionClick (action) {// This function is used to know which commit button is clicked
$ ("# Hidlgc"). val (""); // clear hidden values
$ ("# Hidlgc"). val (action); // assign a value to the hidden control
<Form id = "form1" method = "post" action = "MySession. aspx">
<Td> account: </td> <input type = "text" name = "txtUid"/> </td>'
<Td> password: </td> <input type = "password" name = "txtPwd"/> </td>
<Td colspan = "2">
<Input type = "hidden" value = "" id = "hidlgc" name = "hidlgclick"/>
<Input onclick = "getSessionClick ('lgclick')" type = "submit" value = "login"/>
<Input type = "submit" onclick = "getSessionClick ('getsession')" value = "get session"/>
<Input type = "submit" onclick = "getSessionClick ('backlg ')" value = "log out"/>

. Net code

The code is as follows: Copy code

Protected void Page_Load (object sender, EventArgs e)
// Write the user ID to the session
If (Request. Form ["hidlgclick"] = "lgclick ")
If (Request. form ["txtUid"]. toString () = "admin" & Request. form ["txtUid"]. toString () = "admin") // judge user logon
Session ["userName"] = Request. Form ["txtUid"]. ToString (); // save the user ID to the session.
Response. Write (Session ["userName"]. ToString () + "--- Click Login"); // Get the session and Write it to the page
// Obtain the Session
If (Request. Form ["hidlgclick"] = "getSession ")
If (Session ["userName"]! = Null)
Response. Write (Session ["userName"]. ToString () + "--- click to get session"); // Obtain the session and Write it to the page
// Cancel the current session, which is equivalent to logging out ).
If (Request. Form ["hidlgclick"] = "backLg ")
Session. Abandon ();


So how can we determine if the session has expired?

Method 1: The most stupid method, which is determined in the page_load () method of each page.

The code is as follows: Copy code

If (Session ["UserId"]! = Null)


// Successful login




// Response. write ("<script> alter ('log on to it'); </script> ");


This method requires repeated code to be written on every page. Code redundancy

Method 2: You can check in HttpModule to register the AcquireRequestState of the request pipeline in HttpModule.

Event (the event where the session can be obtained)


1: Create a class Module that inherits the IHttpModule interface

2: Let the Module class implement interface members.

3: register the AcquireRequestState event for the Context in the Init () method (the Session can be obtained in this event)

4: write in the method

The code is as follows: Copy code

Void context_AcquireRequestState (object sender, EventArgs e)


HttpApplication app = (HttpApplication) sender;

If (app. Context. Session ["userId"] = null)


App. Response. Write ("<script> alert ('No logon'); </script> ");



5. Add a node under the <system. web> node in the web. config configuration file.

The code is as follows: Copy code


<Add name = "demo" type = "Module"/> <! -- Type is followed by namespace. Class name -->



By using this method, the module is checked when each page is loaded.

The principle is that the class implementing the IHttpModule interface is executed before the execution page. Before the page_load () event is executed, a message is displayed if the Session is terminated if it does not exist.

This method is more efficient, because it can be processed directly if no session exists. All subsequent events can be executed.

Method 3: Do some operations on the page class

The Page class has the virtual method OnInit.


1: create a class TestSession that integrates the Page class

2: rewrite OnInit () in TestSession.

3: determine the Session in the OnInit () method

4: integrate the TestSession class on the Page to determine the session, instead of inheriting the Page class.

This method is flexible. You only need to inherit TestSession from the Page where you need to determine the session. You do not need to determine whether the session Page inherits the Page directly.

Session functional defects

Currently, ASP developers are using Session, but they have discovered the following defects in ASP Session:

Process dependency: The ASP sessionstate is stored in the iisprogress, and the inetinfo.exe program is also used. When the inetinfo.exe process crashes, the information is lost. In addition, restarting or disabling the IIS service will cause information loss.
Limitations of the range of Session status usage: When a user accesses another website from one website, the Session information will not be migrated. For example, there may be more than one WWW server on the Sina website. After a user logs on, he/she will go to various channels, but each channel is on a different server, what if I want to share Session information on these WWW servers?
Cookie dependency: in fact, the client's Session information is stored in the Cookie. If the client completely disables the Cookie function, it cannot enjoy the function provided by the Session.
In view of the above defects of ASP Session, Microsoft designers are designing and developing ASP. NET Session, and the above defects are completely overcome, making ASP. NET Session has become a more powerful feature.

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