Detailed application of session in ASP.net _ Practical skills

Source: Internet
Author: User
Tags sessions terminates

When a user jumps between pages of an application, the variables stored in the Session object are not purged, and the variables always exist when the user accesses the page in the application. When a user requests a Web page from an application, the Web server automatically creates a Session object if the user does not have a conversation. When a session expires or is discarded, the server terminates the session.

You can manage the session object on the server by sending a unique Cookie to the client program. When a user requests a page in an ASP application for the first time, the ASP checks the HTTP header information to see if a Cookie named ASPSessionID in the message is sent, and if so, the server starts a new session and generates a globally unique value for the session. This value is sent to the client as the value of the new ASPSessionID cookie, which is used to access information that is stored on the server that is part of the client program. The most common function of the session object is to store user preferences. For example, if a user indicates that they don't like to view a graphic, they can store that information in the session object. In addition, it is often used in the process of identifying customer identities. Note that session state is reserved only in browsers that support cookies, and sessions will not work if the customer turns off the cookie option.

(a) The basic attributes of the session:

One, property

1, SessionID

The SessionID property returns the user's session identity. When you create a session, the server generates a separate identity for each session. The session identity is returned with a long shaping data type. In many cases SessionID can be used for WEB page registration statistics.

2, TimeOut

The Timeout property specifies the time-out period for the session object of the application in minutes. If the user does not refresh or request a Web page within the time-out period, the session terminates.

Second, the method

The session object has only one method, that is, the Abandon,abandon method deletes all objects stored in the session object and releases the source of those objects. If you do not explicitly call the Abandon method, the server deletes these objects once the session times out. The following example releases session state when the server finishes processing the current page.

<% Session.Abandon%>

III. Events

The session object has two events that can be used to start and release the session object when it is running.

1, the Session_OnStart event occurs when a new session is created by the server. The server processes the requested page before it is executed. The Session_OnStart event is the best time to set session variables, because they are set before any pages are accessed.

Although the session object persists when the Session_OnStart event contains a Redirect or End method call, the server stops processing the Global.asa file and triggers the script in the file of the Session_OnStart event.

To ensure that a user always starts a session when a particular Web page is opened, the Redirect method can be invoked in the Session_OnStart event. When the user enters the application, the server creates a session for the user and processes the Session_OnStart event script. You can include the script in this event to check that the user opens a page that is not a startup page, and if not, instruct the user to invoke the Response.Redirect method to start the Web page. The procedure is as follows:

< SCRIPT runat=server language=vbscript>
Sub session_onstart
startpage = "/myapp/starthere.asp"
CurrentPage = Request.ServerVariables ("Script_name")
if StrComp (currentpage,startpage,1) then
Response.Redirect (startpage) End-
if End
Sub
</script>

The above programs can only run in browsers that support cookies. Because browsers that do not support cookies cannot return the SessionID cookie, the server creates a new session whenever the user requests a Web page. In this way, the Session_OnStart script is processed for each request server and the user is redirected to the startup page.

2. The Session_OnEnd event was discarded or timed out during the session.

Things to note about using Session Objects application objects are similar, please refer to the preceding text.

Sessions can be started in the following three ways:

1, a new user requests access to a URL that identifies an. asp file in an application, and the application's Global.asa file contains the Session_OnStart process.

2), the user stores a value in the Session object.

3, the user requests an application's. asp file, and the application's Global.asa file uses the < object> tag to create an instance of the object with the session scope.

If a user does not request or refresh any page in the application within a specified time, the session ends automatically. The default value for this period is 20 minutes. You can change the default time-out limit settings for an application by setting the session Timeout property in the Application Options property page in Internet Services Manager. This value should be set based on the requirements of your WEB application and the memory space of the server. For example, if you want users browsing your WEB application to stay only a few minutes per page, you should shorten the default timeout for the session. An overly long session timeout value will cause an open session to run out of memory resources for your server. For a specific session, if you want to set a time-out value that is less than the default time-out, you can set the Timeout property of the Sessions object. For example, the following script sets the timeout value to 5 minutes.

<% Session.Timeout = 5%>

Of course, you can also set a time-out value that is greater than the default setting, and the Session.Timeout property determines the timeout. You can also explicitly end a session by using the Abandon method of the Sessions object. For example, an Exit button is provided in the table, and the ACTION parameter of the button is set to the URL of the. asp file that contains the following commands.

<% Session.Abandon%>

(ii) The use of the session:

First, use the session to set permissions
Session Introduction:
in short, the server gives the client a number. When a WWW server is running, there may be several users browsing the Web site that is being shipped on this server. When each user first connects to the WWW server, he establishes a session with the server, and the server automatically assigns a SessionID to identify the user's unique identity. This SessionID is a 24-character string randomly generated by the WWW server.
Initial use of-session :

protected void Page_Load (object sender, EventArgs e)
{//This is the initialization of the page
  if (! Page.IsPostBack)
  {//To determine whether the initial execution
   if (Object.Equals (session["AdminName", null))
   {//Judge in session[" AdminName "] exists a value
    Response.Redirect (" errorpage.aspx ", True);
   }
   else
   {//If there is a record of this person's username
   name.text = session["AdminName"]. ToString ();}}}

Second, the page transfer value

There are many ways to pass information between pages:
First: You can use QueryString
Second: You can use session
Third: Server.Transfer
These three kinds of means of transmission are both pros and cons, and I'll explain to you in my experience
First: QueryString
QueryString is a very simple way of passing values, the disadvantage of which is to display the value to be passed in the browser's address bar, and this method can not pass the object. If you want to pass a security that is not so important or is a simple value. It's best to use this method.
Here is a small example to illustrate
1. Create a Web page called sendmessage.aspx
2. Add two textbox in the page, called Txtname,txtemail, with a button, called submit

 protected void Submit_click (object sender, EventArgs e)
 {
  String Url = ' receivemessage.aspx? Name= "+
  txtName.Text +" &email= "+ txtemail.text;
  Response.Redirect (URL);
 

3. Again create a receive information page, called Receivemessage.aspx
4. Add two label to the page, called Lbname,lbemail

 protected void Page_Load (object sender, EventArgs e)
 {//Use request to receive the value passed over from the previous page, displayed on the page respectively
  Lbname.text = request.querystring["Name"];
  Lbemail.text = request.querystring["Email"];
 }

-again: Using the session variable
The most common way to use the session variable is to pass the value to the next page and cross over to multiple pages until you remove the value of the session variable before it disappears.
The following examples illustrate
1. Create a page called Sendsession
2. Add two textbox in the page, call Txtname,txtemail, add a button, call submit

 protected void Submit_click (object sender, EventArgs e)
 {//can use the session's Add method
  session["Name"] = txtName.Text;
  You can use Session.add ("Name", txtName.Text);
  session["Email"] = Txtemail.text;
  You can use Session.add ("Email", txtemail.text);
  Response.Redirect ("receivemessage.aspx");
 }

3. Create a page again, called Receivemessage.aspx
4. Add two label to the page, called Lbname,lbemail

 protected void Page_Load (object sender, EventArgs e)
 {
  lbname.text = session[' Name ']. ToString ();
  Lbemail.text = session["Email"]. ToString ();
  session["Name"]. Remove ();
  session["Email"]. Remove ();
  Use end to clear the value in session
 

This is the use of session to pass the numeric value, which consumes the server's resources and uses less
-again: Using Server.Transfer
This transmission is a bit complicated, but it can also be a way of delivering value
The following examples illustrate:
1. Create a page called sendmessage.aspx
2. Add two textbox in the page, call Txtname,txtemail, add a button, call submit

 protected void Submit_click (object sender, EventArgs e)
 {
  Server.Transfer ("receivemessage.aspx");
Add another attribute public
 String Name
 {get
  {
   txtName.Text}}
 }
 Public String Email
 {
   txtemail.text
  }
 }

3. Create a page again, called Receivemessage.aspx
4. Put two label on the page, called Lbname,lbemail

 protected void Page_Load (object sender, EventArgs e)
 {
  //Create an instance of the original form SendMessage WF1
  //Get instantiated handle
  WF1 = (SendMessage) Context.Handler;
  Label1.text=wf1. Name;
  Label2.text=wf1. EMail;
 }

The above is the entire content of this article, I hope that we learn to understand the use of the session in ASP.net help.

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.