ASP. NET status management-session)

Source: Internet
Author: User

ASP. NET allows you to use session status to save Web applications of each activityProgramSession value. The session status is an instance of the httpsessionstate class.

The session status is similar to the application status. The difference is that the session status is limited to the current browser session. If different users are using your application, each user session has a different session status. In addition, if a user exits and returns to the application, the session Status of the second user session will be different from that of the first user session.

Session Status uses a key-value dictionary structure to store session-specific information, which must be maintained between server round-trip and page requests.

You can use session status to complete the following tasks:
1. uniquely identifies browser or client device requests and maps these requests to individual session instances on the server.
2. Store session-specific data on the server for requests from multiple browsers or client devices in the same session.
3. Trigger appropriate session management events. In addition, you can use these events to write applications.Code.

Once the application-specific information is added to the session state, the server manages the object. Based on the options you specify, you can store session information in cookies, out-of-process servers, or computers running Microsoft SQL Server.

By default, ASP. NET session status is enabled for all ASP. NET applications.

 

Session variable
How to: Save the value in the session Status
Session variables are stored in the sessionstateitemcollection exposed through the system. Web. httpcontext. Session attribute.
The session variable set is indexed by the variable name or integer index. You can create a session variable by referencing the session variable by name. You do not need to declare session variables or explicitly add session variables to the set.
For example, the following code example creates a session variable that represents the user's name and last name respectively, and sets them to the value retrieved from the Textbox Control.
Session ["firstname"] = firstnametextbox. text;
Session ["lastname"] = lastnametextbox. text;

By default, session variables can be of any valid. Net type.
For example, the following code example stores the arraylist of values in the session variable "stockpicks. Note that values returned by the "stockpicks" session variable must be forcibly converted to the appropriate type when retrieved from the sessionstateitemcollection.
Arraylist stockpicks = (arraylist) session ["stockpicks"];

Session ["stockpicks"] = stockpicks;

How to: Read values in session Status
In this example, access the item property to retrieve the values in the session status.
String firstname = (string) (session ["first"]);
String lastname = (string) (session ["last"]);
String city = (string) (session ["city"]);

If you try to obtain a value from a session that never exists, no exception is thrown. To ensure that the required value is in the session state, first use the test (for example, the following test) to check whether the object exists:
If (session ["city"] = NULL)
// No such value in session State; take appropriate action.

 

Session identifier
Browser sessions are identified by unique identifiers stored in the sessionid attribute. Session ID enables ASP. NET Applications to associate a specific browser with session data and information on the Web server. The session ID value is transmitted through cookies between the browser and the Web server. If no cookie is specified, the session ID is transmitted through a URL.

No cookie sessionid
By default, sessionid is stored in the cookie of the browser that has not expired sessions. By setting the cookieless attribute to true in the sessionstate section of the web. config file, you can specify not to store session identifiers in cookies.
ASP. NET automatically inserts a unique session ID in the URL of the page to maintain the cookieless session status.
For example, the following URL has been modified by ASP. NET to contain a unique session ID lit3py55t21z5v55vlm25s55:
Http://www.example.com/s (lit3py55t21z5v55vlm25s55)/orderform. aspx

ASP.. Net to modify the Link (without modifying the explicit path) contained in all request pages using the path relative to the application by sending each page to the browser, embed a session ID value in the link. You can maintain the session state as long as you follow the link path provided by the ASP. NET application. However, if the client overwrites the URL provided by the application, Asp. net will not be able to parse this session ID, nor can this request be associated with an existing session, so a new session will be started for this request.

The session ID is embedded with the slash after the application name in the URL before all other files or virtual directory identifiers.

 

Session status event
ASP. NET provides two types of events that help you manage user sessions: session_onstart event and session_onend event. The former is triggered when a new session starts, and the latter is triggered when the session is abandoned or expired.

Session_onstart event
You can add a subroutine named session_onstart to the global. asax file to process the session_onstart event. If a request starts a new session, the session_onstart subroutine runs at the beginning of the request. If the request does not contain the sessionid value or the sessionid attribute contained in the request references an expired session, a new session is started.
You can use the session_onstart event to initialize session variables and track session-related information.

Session_onend event
You can add a subroutine named session_onend to the global. asax file to process the session_onend event. Session_onend subroutine runs when the abandon method is called or the session has expired. If the number of minutes specified by the timeout attribute of a session is exceeded and the session is not requested during this period, the session expires.
Session_onend events are supported only when the session state attribute mode is set to inproc (default. If the session state attribute mode is StateServer or sqlserver, The session_onend event in the global. asax file is ignored. If the session state attribute mode is set to custom, the custom session state storage provider determines whether the session_onend event is supported.
You can use the session_onend event to clear session-related information, such as user information in the data source tracked by the sessionid value.

The following sample code demonstrates a sample session_onstart and session_onend subroutines that can be added to the global. asax file. The child routines defined in this example create a counter to track the number of application users that are using the application. Note that this example will run normally only when the session state attribute mode is set to inproc, because session_onend event is supported only in-process session state storage.
<Script language = "C #" runat = "server">
Public void application_onstart ()
{
Application ["usersonline"] = 0;
}

Public void session_onstart ()
{
Application. Lock ();
Application ["usersonline"] = (INT) application ["usersonline"] + 1;
Application. Unlock ();
}

Public void session_onend ()
{
Application. Lock ();
Application ["usersonline"] = (INT) application ["usersonline"]-1;
Application. Unlock ();
}
</SCRIPT>

 

Session status Mode
ASP. NET session Status supports several storage options for session data. Each option is identified by a value in the sessionstatemode enumeration.
The following list describes available session Status modes:
Inproc mode, which stores the session Status in the memory of the Web server. This is the default setting.
StateServer mode, which stores the session status in a separate process named ASP. NET status service. This ensures that the session status is retained when the web application is restarted and the session status can be used on multiple Web servers in the network farm.
In sqlserver mode, the session status is stored in an SQL Server database. This ensures that the session status is retained when the web application is restarted and the session status can be used on multiple Web servers in the network farm.
Custom mode, which allows you to specify a custom storage provider.
Off mode. This Mode disables the session status.
By allocating a sessionstatemode enumeration value to the mode attribute of the sessionstate element in the web. config file of the application program, you can specify the mode for using the ASP. NET session status. In addition to inproc and off, parameters are required for other modes, such as the connection string value discussed later in this topic. You can view the selected session status by accessing the value of the system. Web. sessionstate. httpsessionstate. mode attribute.

In-process mode
The in-process mode is the default session Status mode, which is specified using the inprocsessionstatemode enumeration value. The in-process mode stores session Status values and variables in the memory of the Local Web server. It is the only mode that supports session_onend events.

Status Server Mode
In StateServer mode, session status is stored in a process called ASP. NET status service. This process is independent of an ASP. NET auxiliary process or a separate process in the IIS application pool. This mode ensures that the session status is retained when the web application is restarted and that the session status can be used on multiple Web servers in the network farm.

SQL Server Mode
In sqlserver mode, the session status is stored in an SQL Server database. This mode ensures that the session status is retained when the web application is restarted and that the session status can be used on multiple Web servers in the network farm.

Custom Mode
The custom mode specifies that you want to use the custom session state storage provider to store session state data. When using mode M mode to configure ASP. NET applications, you must use the providers sub-element of the sessionstate configuration element to specify the type of the session state storage provider. Use the Add sub-element to specify the provider type, including the type attribute of the specified provider type name and the name attribute of the specified provider Instance name. Then, provide the name of the provider instance to the customprovider attribute of the sessionstate element, and configure the ASP. Net session status to use the provider instance to store and retrieve session data.

 

Configure session Status
Use the sessionstate element in the system. Web configuration section to configure the session status. You can also use the enablesessionstate page command to configure the session status.

The sessionstate element can be used to specify the session storage data mode, the method for sending the session Identifier value between the client and server, the Session Timeout value, and the supported value based on the session mode. For example, the following sessionstate element configures the application to the SQL Server session mode with a timeout value of 30 minutes and specifies that the session identifier is stored in the URL.

<Sessionstate mode = "sqlserver"
Cookieless = "true"
Regenerateexpiredsessionid = "true"
Timeout = "30"
Sqlconnectionstring = "Data Source = mysqlserver; Integrated Security = sspi ;"
Statenetworktimeout = "30"/>

You can disable the session Status of an application by setting the session Status mode to off. If you only want to disable the session Status of a specific page of the application, you can set the enablesessionstate page command to false. Note: You can also set the enablesessionstate page command to readonly to provide read-only access to session variables.

 

Concurrent requests and session Status
Access to the ASP. NET session status belongs to each session, which means that if two different users send requests at the same time, the access to each individual session will be granted at the same time. However, if the two concurrent requests are for the same session (that is, the same sessionid value is used), the first request received will obtain exclusive access to the session information, the second request will be executed after the first request is completed, or until the first request exclusive lock on the information is released because the first request exceeds the lock timeout. If the enablesessionstate page command is set to readonly, requests for read-only session information will not cause exclusive lock on session data. The read-only requests to session data may not be satisfied until the lock obtained by the read/write requests is removed.

 

 

 

Http://aierong.cnblogs.com
SQL server2005 Transact-SQL new weapon learning Summary-Summary
Ms SQL database backup and recovery stored procedures (enhanced)
SQL Server Distributed Query essay (sp_addmediaserver) and remote login ing (sp_addmediasrvlogin) use small summary)
WAP development data station (latest update)
Custom Format String (implementation of the three interfaces of iformattable, iformatprovider, and icustomformatter)
Asynchronous programming of mcad learning notes (asynccallback delegation, iasyncresult interface, begininvoke method, and endinvoke method)
Mcad learning notes: Calling class methods through reflection, attention, fields, indexers (2 methods)
Serialization of mcad learning notes (binary and soap serialization)
Delegated re-understanding of mcad learning notes (discussion of Delegate constructor, begininvoke, endinvoke, and invoke4 methods)
Winform development, form display, and form value passing knowledge
Microsoft Windows service using mcad Study Notes
Copy all the objects and files under a certain category to the target category (number of objects)
ASP. NET status management (Summary)

 

 

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.