Asp.net session usage and expired instance code

Source: Internet
Author: User

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:

Copy codeThe Code is as follows:
<%
If Session ("PageViewed") = "" Then
Session ("PageViewed") = 1
Else
Session ("PageViewed") = Session ("PageViewed") + 1
End If
%>

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


Copy codeThe Code is as follows:
<%
Response. Write ("You have viewed" & Session ("PageViewed") & "pages ")
%>


Session usage

Copy codeThe Code is as follows:
<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
}
</Script>
</Head>
<Body>
<Form id = "form1" method = "post" action = "MySession. aspx">
<Table>
<Tr>
<Td> account: </td> <input type = "text" name = "txtUid"/> </td>'
</Tr>
<Tr>
<Td> password: </td> <input type = "password" name = "txtPwd"/> </td>
</Tr>
<Tr>
<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"/>
</Td>
</Tr>
</Table>
</Form>
</Body>

. Net code

Copy codeThe Code is as follows:
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.


Copy codeThe Code is as follows:
If (Session ["UserId"]! = Null)

{

// Successful Login

}

Else

{

// 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)

Step:

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

Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
<HttpModules>

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

</HttpModules>


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.

Step:

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