Explain the usage of Session in ASP. NET in detail

  • 2021-07-22 09:32:56
  • OfStack

The variables stored in the Session object are not cleared when the user jumps between pages in the application, but remain when the user accesses the page in the application. When a user requests an Web page from an application, the Web server automatically creates an Session object if the user does not have a session. When the session expires or is abandoned, the server terminates the session.

The Session object on the server can be managed by sending a 1-only Cookie to the client. When a user first requests a page in an ASP application, ASP should check the HTTP header information to see if there is an Cookie named ASPSESSIONID sent in the message. If there is, the server will start a new session and generate a global only 1 value for the session. When this value is sent to the client as the value of the new ASPSESSIONID Cookie, it is using this Cookie that can access the information stored in the server belonging to the client program. The most common purpose of the Session object is to store the user's preferences. For example, if the user indicates that he does not like viewing graphics, he can store this information in an Session object. In addition, it is often used in the procedure of authenticating customers. Note that session state is retained only in browsers that support cookie, and if the customer turns off the Cookie option, Session will not work.

(1) Basic properties of Session:

1. Attributes

1. SessionID

The SessionID property returns the user's session identity. When creating a session, the server generates a separate identity for every 1 session. The session identity is returned as a long shaped data type. In many cases, SessionID can be used for WEB page registration statistics.

2. TimeOut

The Timeout property specifies a timeout in minutes for the application's Session object. If the user does not refresh or request the web page within the timeout period, the session will terminate.

2. Methodology

The Session object has only one method, the Abandon, and the 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 will delete these objects if the session times out by 1 denier. The following example releases session state when the server finishes processing the current page.

< % Session.Abandon % >

3. Events

The Session object has two events that can be used in the Session object startup and release are running procedures.

1. The Session_OnStart event occurs when the server creates a new session. The server processes the script before executing the requested page. The Session_OnStart event is the best time to set session variables because they are set before any page is accessed.

Although the Session object persists if the Session_OnStart event contains an 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 opening a particular Web page, you can call the Redirect method 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 a script in this event to check whether the page opened by the user is a startup page, and if not, instruct the user to call the Response. Redirect method to start the 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 program can only run in browsers that support cookie. Because browsers that do not support cookie cannot return SessionID cookie, the server creates a new session every time a user requests an Web page. Thus, for each requesting server, the Session_OnStart script will be processed and the user will be redirected to the startup page.

2. The Session_OnEnd event occurs when the session is abandoned or timed out.

Considerations for using Session objects are similar to Application objects, see above.

A session can be started in three ways:

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

2) The user stores 1 value in the Session object.

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

If the user does not request or refresh any pages in the application within the specified time, the session ends automatically. The default value for this period is 20 minutes. You can change the default timeout limit settings for your application by setting the Session Timeout property in the Application Options property page in the Internet Service Manager. This value should be set according to 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 for only a few minutes per 1 page, you should shorten the default timeout value for the session. An excessively long session timeout value will cause too many open sessions to deplete your server's memory resources. For a specific session, if you want to set a timeout value that is less than the default timeout value, you can set the Timeout property of the Session object. For example, the following script sets the timeout value to 5 minutes.

< % Session.Timeout = 5 % >

Of course, you can also set a timeout value that is greater than the default setting. The Session. Timeout property determines the timeout value. You can also explicitly end a session through the Abandon method of the Session object. For example, provide an "exit" button in the table, and set the ACTION parameter of the button to URL of the. asp file containing the following commands.

< % Session.Abandon % >

(2) Usage of Session:

1. Use Session to set permissions
Introduction to Session:
Simply put, it is a number given by the server to the client. When an WWW server is running, there may be several users browsing the Web site running on that server. When each user first establishes a connection with this WWW server, he establishes an Session with this server, and the server will automatically assign him an SessionID to identify the only identity of this user. 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)
  {// Judge whether it is the first execution 
   if (Object.Equals(Session["AdminName"], null))
   {// Judge at Session["AdminName"] Is there a value 
    Response.Redirect("ErrorPage.aspx", true);
   }
   else
   {// If it exists, record the user name of this person 
   Name.Text = Session["AdminName"].ToString();
   }
  }
}

2. Page value transfer

There are many ways to pass information between pages:
1: You can use QueryString
Part 2: You can use Session
Section 3: Server. Transfer
These three methods of value transfer have advantages and disadvantages. Let me explain it to you with my experience.
First: QueryString
QueryString is a very simple way to pass a value. Its disadvantage is that the value to be passed will be displayed in the address bar of the browser, and this method cannot pass an object. If you want to pass a value that is not so important in security or a simple value. It's best to use this method.
The following is a small example to illustrate the following 1
1. Create an Web page called SendMessage.aspx
2. Add two TextBox called TxtName and TxtEmail and one Button called Submit to the page


 protected void Submit_Click(object sender, EventArgs e)
 {
  String Url = "ReceiveMessage.aspx?Name=" +
  TxtName.Text + "&Email=" + TxtEmail.Text;
  Response.Redirect(Url);
 }

3. Create another receive message page called ReceiveMessage. aspx
4. Add two Label to the page, called LbName and LbEmail


 protected void Page_Load(object sender, EventArgs e)
 {// Use Request To receive the values passed from the previous page and display them on the page 
  LbName.Text = Request.QueryString["Name"];
  LbEmail.Text = Request.QueryString["Email"];
 }

-Again: Use the Session variable
Using Session variable to pass value is one of the most common ways, this way can not only pass the value to the next page, but also cross-pass to multiple pages, until the value of Session variable Remove, it disappears
Here's an example
1. Create a page called SendSession
2. Add two TextBox called TxtName and TxtEmail and one Button called Submit to the page


 protected void Submit_Click(object sender, EventArgs e)
 {// You can use the Session Adj. Add Method 
  Session["Name"] = TxtName.Text;
  // You can use the Session.Add("Name",TxtName.Text);
  Session["Email"] = TxtEmail.Text;
  // You can use the Session.Add("Email",TxtEmail.Text);
  Response.Redirect("ReceiveMessage.aspx");
 }

3. Create another page called ReceiveMessage. aspx
4. Add two Label to the page, called LbName and 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();
  // To clear at the end of use Session Value in 
 }

This is to use Session to pass values, which consumes server resources and uses as little as possible
-Again: use Server. Transfer
This transfer is a bit complicated, but it can also be a value transfer method
Here is an example of 1:
1. Create a page called SendMessage. aspx
2. Add two TextBox called TxtName and TxtEmail and one Button called Submit to the page


 protected void Submit_Click(object sender, EventArgs e)
 {
  Server.Transfer("ReceiveMessage.aspx");
 }
// Add again 1 Attributes 
 public String Name
 {
  Get
  {
   return TxtName.Text;
  }
 }
 public String Email
 {
  Get
  {
   return TxtEmail.Text;
  }
 }

3. Create another page called ReceiveMessage. aspx
4. Put two Label on the page, called LbName and LbEmail


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

The above is the whole content of this article, hoping to help you learn and understand the usage of Session in ASP. NET.


Related articles: