ASP. NET session Detailed notes

Source: Internet
Author: User
Tags session id

(i) Description

When a user navigates an ASP. NET page in a WEB application, the ASP. NET session state enables you to store and retrieve the user's values. HTTP is a stateless protocol. This means that the WEB server will process each HTTP request for the page as a separate request. The server does not retain any information about the value of the variable that was used during the previous request.

The ASP. NET session state identifies requests from the same browser within a limited time range as a single session, and when each user first establishes a connection to the WWW server, he sets up a session with the server, and the server automatically assigns it a SessionID. The unique identity used to identify the user. Session provides a way to preserve variable values for the duration of the session. By default, ASP. NET session state is enabled for all ASP.

Session variables can be any valid. NET Framework type, note: When using a session state mode other than InProc, the session variable type must be a primitive. NET type or a serializable type. This is because the session variable values are stored in the external data store.

The session is identified by a unique identifier, which can be read using the SessionID property. When session state is enabled for an ASP. NET application, the SessionID values that are sent by the browser are checked for each page request in the application. If no SessionID value is provided, ASP. NET starts a new session and sends the session's SessionID value along with the response to the browser.

By default, the SessionID value is stored in a Cookie. However, the application can also be configured to store SessionID values in the URL of a "no Cookie" session. As long as the request is sent using the same SessionID value, the session is considered active. If the request interval for a particular session exceeds the specified time-out value (in minutes), the session is considered expired. A request that is sent with an expired SessionID value generates a new session.

Safety instructions:

Whether as a Cookie or as part of a URL, the System.Web.SessionState.HttpSessionState.SessionID value is sent in clear text. A malicious user can access another user's session by obtaining a SessionID value and including it in a request to the server. If you store sensitive information in session state, it is recommended 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 current session Cookie. However, by setting the cookieless property to true in the sessionstate section of the Web. config file, you can specify that the session identifier should not be stored in a Cookie.

<configuration>
<system.web>
<sessionstate cookieless= "true"
Regenerateexpiredsessionid= "true"/>
</system.web>
</configuration>

ASP. NET maintains a Cookie-free session state by automatically inserting a unique session ID in the URL of the page. For example, the following URL has been modified by ASP. Lit3py55t21z5v55vlm25s55 to include a unique session ID:
http://www.example.com/(S (LIT3PY55T21Z5V55VLM25S55))/orderform.aspx

(ii) Configuring session state

Session state can be configured by using the sessionstate element of the system.web configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive.

Use the sessionstate element to specify the following options:

    • The mode used by the session to store the data.

    • The way the session identifier value is sent between the client and the server.

    • The timeout value of the session.

    • Supports the values based on the session Mode setting.

The following example shows a sessionstate element that configures the SQL Server session mode for the application. This element sets the Timeout value to 30 minutes and specifies that the session identifier is stored in the URL.

<!----><sessionstate mode= "SQL Server"
Cookieless= "true"
Regenerateexpiredsessionid= "true"
timeout= "30"
sqlconnectionstring= "Data source=mysqlserver;integrated Security=sspi;"
statenetworktimeout= "/>
"

You can disable session state for an application by setting the session state mode to OFF. If you only want to disable session state for a particular page of your application, you can set the EnableSessionState value in the @ Page directive to false. You can also set the EnableSessionState value to ReadOnly to provide read-only access to session variables.
Note: Timeout refers to the time of the session, in minutes, that is, if the client does not broadcast a request to the server during timeout, the session terminates and all session data is lost.

(iii) session mode

The ASP. NET session state supports several storage options for session data. Each option is identified by a value in the Sessionstatemode enumeration. The following list describes the available session-state modes:

    • InProc mode, which stores session state in memory on the WEB server. This is the default setting.

    • StateServer mode, this mode stores session state in a separate process called the ASP. NET State Service. This ensures that session state is preserved when the WEB application is restarted and that session state is available to multiple Web servers in the Web farm.

    • SQL Server mode stores the session state in a database of SQL Servers. This ensures that session state is preserved when the WEB application is restarted and that session state is available to multiple Web servers in the Web farm.

    • Custom mode, this mode allows you to specify a customized storage provider.

    • Off mode, this mode disables session state.

You can specify the mode that you want to use for the ASP. NET session state by assigning a Sessionstatemode enumeration value to the Mode property of the sessionstate element in the application's Web. config file. In addition to InProc and OFF, other modes require additional parameters, such as connection string values that will be discussed later in this topic. By accessing the value of the Httpsessionstatemode property, you can view the currently selected session state.

(iv) 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" >
<title>untitled page</title>
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:button id= "Mloginbutton" runat= "Server" text= "Login"
onclick= "Mloginbutton_click"/>
</div>
</form>
</body>

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 ">

<title>session sample</title>
<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>

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. Example of different modes, configuring Web. config

A. InProc mode

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

(1) test page, after two minutes then click Get Session will return to Login.aspx page, because the session expires

(2) Restart the Web service, click Get Session will return to the Login.aspx page, because the session is missing

B. StateServer mode

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

(1) Start the ASP.

(2) Modify the sessionstate as follows

<sessionstate mode= "StateServer" timeout= "stateconnectionstring=" >

</sessionState>

(3) Restart the Web server, click Getsession,session 10 minutes will not be lost, because the session storage server in another aspnet_state process

c. SQL Server Mode

Describe:

In the case of SQL Server mode, objects stored in session state must be serializable
By default, the Aspnet_regsql.exe tool creates a database named ASPState that contains stored procedures that support SQL Server mode. By default, session data itself is stored in the tempdb database. You can choose to use the-sstype option to change where session data is stored. The following table shows the possible values for 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 you restart SQL Server.
P: The session data is stored in the ASPState database instead of stored in the tempdb database.
C: Store session data in a custom database. If you specify the C option, you must also use the-D option to include the name of the custom database.
(1) Enter Visual Studio (2005) command prompt
(2) Enter the following red command

(3) Create the following database and table

(4) Run the page and restart the Web service, click Get Session,session is not lost because the Session is saved to the SQL Server database.


ASP. NET session Detailed notes

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.