Detailed notes on ASP. NET sessions and asp. netsession

Source: Internet
Author: User

Detailed notes on ASP. NET sessions and asp. netsession
(1) Description

When users navigate ASP. NET pages in Web applications, ASP. NET session status enables you to store and retrieve user values. HTTP is a stateless protocol. This means that the Web server processes each HTTP request on the page as an independent request. The server does not retain any information about the variable values used in the previous request process.

ASP. NET session Status identifies requests from the same browser within a limited time range as a session. When each user establishes a connection with this WWW server for the first time, he creates a Session with the server, and the server automatically assigns a SessionID to identify the user. Session provides a method for retaining the variable value during the Session duration. By default, ASP. NET session status is enabled for all ASP. NET applications.

Session variables can be any valid. NET Framework type. Note: When session state mode other than InProc is used, the session variable type must be of the base element. NET type or serializable type. This is because the session variable value is stored in the external data storage area.

A session is identified by a unique identifier and can be read using the SessionID attribute. When session status is enabled for an ASP. NET application, the system checks whether the SessionID value sent by the browser exists for each page request in the application. If no SessionID value is provided, ASP. NET starts a new session and sends the SessionID value of the session to the browser along with the response.

By default, SessionID values are stored in cookies. However, you can also configure the application to store the SessionID value in the URL of the "No Cookie" session. As long as the same SessionID value is used to send requests, sessions are considered active. If the request interval for a specific session exceeds the specified timeout value (in minutes), the session is deemed to have expired. A new session is generated for requests sent with an expired SessionID value.

Security description:

System. Web. SessionState. HttpSessionState. SessionID is sent in plain text, whether it is a Cookie or a part of a URL. Malicious users can access sessions of another user by obtaining the SessionID value and including it in requests to the server. If you store sensitive information in the session state, we recommend that you use SSL to encrypt any communication between the browser and the server that contains the SessionID value.

By default, the SessionID value is stored in the browser's non-expired session Cookie. However, by setting the cookieless attribute to true in the sessionState section of the Web. config file, you can specify that session identifiers should not be stored in cookies.

<Configuration>
<System. web>
<SessionState cookieless = "true"
RegenerateExpiredSessionId = "true"/>
</System. web>
</Configuration>

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

(2) configuring session Status

You can configure the session status by using the sessionState element in the system. web configuration section. You can also configure the session status by using the EnableSessionState value in the @ Page command.

Use the sessionState element to specify the following options:

  • The mode in which session data is stored.

  • The method by which the session Identifier value is sent between the client and the server.

  • The Timeout value of the session.

  • Supports the value set based on the session Mode.

The following example shows a sessionState element that configures the SQLServer session mode of the application. This element sets the Timeout value to 30 minutes and specifies to store the session identifier 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 value in the @ Page command to false. You can also set the EnableSessionState value to ReadOnly to provide read-only access to session variables.
Note: timeout refers to the session time, in minutes. If the client does not send a request to the server within the timeout time, the session ends and all session data is lost.

(3) Session 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 status of the selected session by accessing the value of the HttpSessionStateMode attribute.

(4) Example

1. Login. aspx

 

<! ----> <% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Login. aspx. cs" Inherits = "Login" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> Untitled Page </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: Button ID = "mLoginButton" runat = "server" Text = "Login"
Onclick = "mLoginButton_Click"/>
</Div>
</Form>
</Body>
</Html>

Login. aspx. cs
Public partial class Login: System. Web. UI. Page

{

Protected void Page_Load (object sender, EventArgs e)

{
 

}

Protected void mLoginButton_Click (object sender, EventArgs e)

{

Session ["loginName"] = "Jack Wang" + DateTime. Now. ToString ();

Response. Redirect ("Default. aspx ");

}

}

2. Default. aspx page

<! ----> <% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN ""
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> Session Sample </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: Button ID = "mGetSessionButton" runat = "server" Text = "Get Session"
Onclick = "mGetSessionButton_Click"/>
<Asp: Label ID = "mShowSessionContentLabel" runat = "server"> </asp: Label>
</Div>
</Form>
</Body>
</Html>

Default. aspx. cs

Public partial class _ Default: System. Web. UI. Page

{

Protected void Page_Load (object sender, EventArgs e)

{

// Response. AddHeader ("Refresh", (Session. Timeout * 1000). ToString () + "; URL = Login. aspx ");

If (string. IsNullOrEmpty (Session ["loginName"] as string ))

{

Response. Redirect ("Login. aspx ");

}

}

Protected void mGetSessionButton_Click (object sender, EventArgs e)

{

MShowSessionContentLabel. Text = "<br> Now is:" + DateTime. Now. ToString () + "<br> Session Content:" +

Session ["loginName"] as string + "<br> SessionId:" + Session. SessionID. ToString ()

+ "<Br> session start time:" + Session ["startTime"] as string;

}

 

3. Configure web. config in different modes.

A. InProc Mode 

<sessionState mode="InProc" timeout="2"></sessionState>        

(1) On the test page, after two minutes, click Get Session to return to the Login. aspx page because the session has expired.

(2) restart the web service and click Get Session to return to the Login. aspx page because the session is lost.

B. StateServer mode

Note: If the mode is set to StateServer, the objects stored in the session state must be serializable.

(1) Start ASP. NET State Service

(2) Modify SessionState as follows:

<SessionState mode = "StateServer" timeout = "10" stateConnectionString = "tcpip = 127.0.0.1: 42424">

</SessionState>

(3) restart the web server and click GetSession. The session will not be lost within 10 minutes because the session is stored in another aspnet_state process on the server.

C. SQL server Mode

Description:

In SQL Server mode, objects stored in session state must be serializable.
The aspnet_regsql.exe tool will create a database named ASPState, which contains stored procedures in SQLServer mode. By default, session data is stored in the tempdb database. You can choose to use the-sstype option to change the storage location of session data. The following table lists the possible values of the-sstype option:
T: store session data in the SQL Server tempdb database. This is the default setting. If session data is stored in the tempdb database, session data is lost when SQL Server is restarted.
P: store session data in the ASPState database instead of the tempdb database.
C: store session data in a custom database. If the c option is specified, you must also use the-d option to include the name of the custom database.
(1) Enter visual studio 2008 (2005) command prompt
(2) enter the following red command:

(3) create the following databases and tables

(4) run the page, restart the web service, and click Get Session. The session will not be lost because the session is saved to the SQL server database.


 

 


Session usage in ASPNET

When you need to save some data in the system, you can use Session! The procedure is as follows:
If the user successfully logs on to the system, the user's user name, password, ID, and other data can be stored in the Session record, so that other pages in the system can be used! When the user name and password are correct, enter the system and write the code: Session ["userName"] = txtUserName. text: string userName = Session ["userName"]. toString ();
Note: txtUserName is the text box ID of the input user name.

Session usage in aspnet

You can regard the SESSION as an array of global variables and assign the value to SESSION ["id"] = "hello" SESSION ["id"]. The current value is "hello ", you can reference it on any web page. String a; a = SESSION ["id"]. Now a is "hello ".

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.