asp.net session usage and outdated instance code _ practical Tips

Source: Internet
Author: User

1.Session is one of the most common states in a Web session.

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

3. The seesion of each client is stored independently.

4. The session information is saved as long as the SessionID cookie is not lost throughout the conversation.

5.Session cannot be accessed across processes and can only be accessed by users of that session. The ID of the fetch session data should be saved in a cookie to the visitor's browser's cache.

6. When the session terminates, or expires, the server clears the sessions object.

7.Session is often used to save the ID of the logged-on user.

The data saved by 8.Session is a cross page global type.

For example, we would like to know if the users visiting our site have browsed through several pages, and we may include them in each page that the user may visit:

Copy Code code as follows:

<%
If session ("pageviewed") = "" Then
Session ("pageviewed") = 1
Else
Session ("pageviewed") = Session ("pageviewed") + 1
End If
%>

The following sentence lets users know that they have browsed through several pages:


Copy Code code as follows:

<%
Response.Write ("have viewed" & Session ("Pageviewed") & "pages")
%>


Use of Session

Copy Code code as follows:

<title></title>
<script src= "Scripts/jquery-1.4.1.min.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
function Getsessionclick (action) {//It is to know which submit button is clicked
$ ("#hidlgc"). Val (""); Empty hidden values
$ ("#hidlgc"). Val (action); Assigning values to a hidden control
}
</script>
<body>
<form id= "Form1" method= "Post" action= "mysession.aspx" >
<table>
<tr>
<td> account: </td><td><input type= "text" name= "Txtuid"/></td> "
</tr>
<tr>
<td> Password: </td><td><input type= "password" name= "Txtpwd"/></td>
</tr>
<tr>
&LT;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= "Exit Login"/>
</td>
</tr>
</table>
</form>
</body>

. NET code

Copy Code code as follows:

protected void Page_Load (object sender, EventArgs e)
{
Write user ID to session
if (request.form["hidlgclick"] = = "Lgclick")
{
if (request.form["Txtuid"]. ToString () = = "Admin" &&request.form["Txtuid"]. ToString () = "admin")//Judge User Login
{
session["userName"] = request.form["Txtuid"].  ToString (); Save User ID to session
Response.Write (session["UserName"). ToString () + "---click Login"); Get session and write to page
}
}
Get session
if (request.form["hidlgclick"] = = "GetSession")
{
if (session["userName"]!= null)
{
Response.Write (session["UserName"). ToString () + "---Click to get Session"); Get session and write to page
}
}
Canceling the current session is equivalent to logging off (logging out).
if (request.form["hidlgclick"] = = "BACKLG")
{
Session.Abandon ();
}
}


So how do we determine if the session is expired?

Method One: The Stupidest method is judged in the Page_Load () method of each page.


Copy Code code as follows:

If (session["UserId"]!=null)

{

Landing success situation

}

Else

{

Response.Write ("<script>alter") ("Please login ');</script>");

}


This method needs to write duplicate code on every page. Code redundancy

Method Two: Can judge in the HttpModule, registers the request pipeline in the HttpModule acquirerequeststate

Event (the event that can get the session)

Step-Playing:

1: Create a new class module that inherits the IHttpModule interface

2: Let the module class implement interface members.

3: Registering the context in the Init () method AcquireRequestState event (can get session in this event)

4: Write in the method

Copy Code code 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 login ');</script>");

}

}


5: Add a node under the <system.web> node in the Web.config configuration file
Copy Code code as follows:

<add name= "Demo" type= "Module"/> <!--type is followed by a namespace. Class name-->


Using this method, you check the module first when each page is loaded.

The principle is that classes that implement the IHttpModule interface are executed before the page is executed. Before the Page_Load () event is executed, the session is prompted if it does not exist.

This method is more efficient because it can be handled directly if there is no session. Subsequent series of events can be performed without execution.


Method Three: Do something on the page class

The virtual method in the page class is OnInit ().

Step-Playing:

1: Create a class that integrates the page class Testsession

2: Rewrite the OnInit () method in Testsession.

3: Judge the session in the OnInit () method

4: In the need to judge the session of the page integration Testsession this class, rather than inheriting the page class

This method is more flexible, in the need to judge the session of the page to inherit testsession can be, do not need to judge the page of the session directly inherit pages on the line


The function of the session is flawed

At present, ASP's developers are using the session this powerful feature, but in their use of the process has found that the ASP session has the following defects:

Process dependencies: ASP session state is stored in the process of IIS, that is, inetinfo.exe this program. So when the Inetinfo.exe process crashes, the information is lost. In addition, the restart or shutdown of the IIS service can result in loss of information.
Limitations of Session state usage: When a user accesses another Web site from a Web site, the sessions information is not migrated over. For example: Sina Web site's www server may be more than one, a user login to go to each channel to browse, but each channel on a different server, if you want to share session information in these WWW server how to do?
Cookie dependencies: In fact, the client's session information is stored in the cookie, and if the client completely disables the cookie function, he will not be able to enjoy the function provided by the session.
In view of the above defects of ASP session, the designers of Microsoft have made corresponding improvement in the design and development of ASP.net session, completely overcome the above defects, make asp.net session become a more powerful function.

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.