Session status in asp.net

Source: Internet
Author: User

In many programs, a session is also called a Session state. It is used to maintain information related to the current browser instance. It is often used for user login to save information or a simple shopping cart.

Session, also known as Session status, is the most common status in the Web system and is used to maintain information related to the current browser instance. For example, we can put the username of the logged-on user in the Session, so that we can determine whether the user is logged on by judging a Key in the Session. If the user is logged on, the username is the same.

We know that the Session is a "manual copy" for each client (or browser instance). When a user establishes a connection with the Web server for the first time, the server will distribute a SessionID to the user as the identifier. SessionID is a random string consisting of 24 characters. Each time a user submits a page, the browser will include this SessionID in the HTTP header and submit it to the Web server, so that the Web server can distinguish the client of the current request page. Which of the following modes are provided for storing SessionID in ASP. NET 2.0:

· Cookie (default ). If the client disables the use of cookies, the Session will also become invalid.

· URL. Enabling or not a Cookie does not affect Session usage. However, you cannot use absolute links.

As mentioned above, SessionID can be stored in the Cookie or URL of the client. Where is the actual Session content stored? ASP. NET 2.0 also provides multiple Session content storage modes.

· InProc (default ). Sessions are stored in IIS processes (Web server memory ).

· StateServer. Sessions are stored in an independent Windows service process (which may not be a Web server ).

· SqlServer. The Session is stored in the SqlServer database table (SqlServer server ).

Although sessions in InProc mode are directly stored in IIS processes on the Web server, the speed is relatively fast, but every time you restart IIS, the Session will be lost. With the last two modes, we can completely separate sessions from the Web server, so as to relieve the pressure on the Web server and reduce the probability of Session loss.

Therefore, SessionID is stored on the client (which can be a Cookie or URL), and others are stored on the Server (which can be an IIS process, an independent Windows service process, or an SQL Server database ).

12.3.2 Session usage
Let's first practice how to use the Session and then answer the second question: the type limitation of Session storage. The Session can be used without any configuration (the default mode is InProc and the Cookie is dependent ). First, create two buttons on the page.

 

In the btn_WriteSession button's Click Event processing method, two sessions are written. One is a simple string and the other is a custom class.

The Code is as follows: Copy code

Protected void btn_WriteSession_Click (object sender, EventArgs e)

{

Session ["SimpleString"] = "happy programming ";

MyUser user = new MyUser ();

User. sUserName = "Xiao Zhu ";

User. iAage = 24;

Session ["CustomClass"] = user;

}

Session usage is very simple. You can directly assign values to the Session of a Key. The custom class MyUser is as follows:

The Code is as follows: Copy code

Class MyUser

{

Public string sUserName;

Public int iAage;

Public override string ToString ()

{

Return string. Format ("Name: {0}, age: {1}", sUserName, iAage );

}

}

Here, we overwrite the ToString () method to directly return some information about the instance. Double-click btn_ReadSession to read data from the Session:

The Code is as follows: Copy code

Protected void btn_ReadSession_Click (object sender, EventArgs e)

{

If (Session ["SimpleString"] = null)

{

Response. Write ("failed to read simple string
");

}

Else

{

String s = Session ["SimpleString"]. ToString ();

Response. Write (s +"
");

}

If (Session ["CustomClass"] = null)

{

Response. Write ("failed to read simple custom class
");

}

Else

{

MyUser user = Session ["CustomClass"] as MyUser;

Response. Write (user. ToString () +"
");

}

}

Before reading the value of a Session, you must first determine whether the Session is empty. Otherwise, the exception "the object reference is not set to the instance of the object" may occur. We can see that all the data read from the Session is of the object type. We need to convert the data type before using it. Open the page, click the write Session button, and then click the read Session button. The page output is shown in Figure 12-1.

 

12.3.3 store sessions in independent processes
In this case, the Session can store any object, right? It is too early to come to this conclusion, because we have never practiced Session in StateServer and SqlServer mode. To store a Session in a Windows service process, perform the following steps.

Step n is to open the status service. Open the "control panel"> "Administrative Tools"> "services" command, find ASP. NET Status Service, right-click the service, and choose start, as shown in figure 12-2.

 

Figure 12-2 start ASP. NET Status Service

N if you officially decide to use the status service to store sessions, do not forget to change the service to self-start (the service can be started after the operating system is restarted) so that you do not forget to start the service and the website Session cannot be used, as shown in figure 12-3, double-click the service to set the Service Startup type to automatic.

 

Figure 12-3 modify the Service Startup type to automatic

After the service is started normally, you can view the progress page of the task manager. The aspnet_state.exe process is a state service process, as shown in 12-4.

 

Figure 12-4 view the process page of the task manager

N Step 4: add the following to the system. web node:


StateNetworkTimeout = "20">

N stateConnectionString indicates the communication address (IP: Service port number) of the Status server ). Because we are now testing on the local machine, set the cost machine address 127.0.0.1 here. The default listening port of Status Service is 42422. You can also modify the port number of the Status Service by modifying the registry.

N 1. Enter regedit at run to start the Registry Editor.

N 2. Open the HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesaspnet_stateParameters node in sequence, and double-click the Port option, as shown in figure 12-5.

Select base number in decimal format and enter a port number. The stateNetworkTimeout attribute indicates the maximum time for the server to request Session data from the status server. The default value is 10 seconds. If the network connection is not good, set this number to a greater value.

N step 1 open the page and click "Write Session". The system reports an error, as shown in 12-6.

Figure 12-5 modify the status service port number Figure 12-6 An error occurred while writing a custom class to the default Session of StateServer.

The prompt is clear. objects can be stored in the service only after being labeled as serialized. What is serialization? Serialization refers to the process of storing the status of the object instance to the storage media. In this process, the object's public and private fields and class names are converted into byte streams, and then the byte streams are written into the data stream. When the object is deserialized, a copy identical to the original object will be created. To make a class Serializable, the simplest way is to mark it using the Serializable attribute.

The Code is as follows: Copy code

[Serializable]

Class MyUser

{

Public string sUserName;

Public int iAage;

Public override string ToString ()

{

Return string. Format ("Name: {0}, age: {1}", sUserName, iAage );

}

}

Step n re-open the page for testing. The result is the same as that in InProc mode.

12.3.4 store sessions in the database
To store sessions in SqlServer, these steps are basically the same.

N 1. Enter cmd in the command line window and run the following command in the command line.

C: WINDOWSMicrosoft.NETFrameworkv2.0.50727aspnet_regsql.exe-S. SqlExpress-E-ssadd

C: Windows is replaced by your own Windows directory, and v2.0.50727 is replaced by the version number of the 2.0 Framework you have installed. -S specifies the SqlServer server address.-E indicates a trusted connection, and-ssadd indicates support for adding status services to the SqlServer server. After the operation, you can use the IDE server resource manager to connect to the SqlExpress database. You can see that there is an additional ASPState database, But the strange thing is that there are many stored procedures in the database without any tables, 12-7.

In fact, all Session data is stored in the tempdb database, as shown in 12-8.

Figure 12-7 use server resource manager to browse the ASPState database Figure 12-8 tempdb database storing Session data

In fact, aspnet_regsql.exe has a-sstype parameter that can be used to specify the content of the Session and the table stored in the stored procedure of the operation. The article details are not provided here. Readers can use aspnet_regsql.exe /? To view the detailed usage of the program.

N 2. Open the Web. config file and modify the sessionState node created earlier.


Specify the previously used connection string for the sqlConnectionString attribute. The only difference is that you do not need to specify the name of the data table. The sqlCommandTimeout attribute indicates the maximum time allowed for SQL command execution. The default value is 30 seconds. You can adjust this number as needed. Finally, re-open the page for testing. The result is the same as that in InProc mode (you also need to ensure that [Serializable] is marked before the custom class). however, we can feel that the speed is a little slow. After all, the data is read or saved from the database, and must be serialized and deserialized before use.

Therefore, sessions can be stored in the following types: InProc mode is of all types, and StateServer and SqlServer mode is of all serializable types.

12.3.5 use range and size limit of Session
What is the range and size limit of session status? We can analyze the status of a Session from 12 to 8. The system uses two tables to store the Session status. There is an ASPStateTempApplication table used to store the application where the Session is located. To some extent, it reflects that the Session cannot be cross-application. For example, we have created two websites on the computer and used Session ["UserName"] To save the Login User Name. After a Website user logs on, when another website directly accesses Session ["UserName"], no value is obtained. So can sessions be cross-user? We know from the previous analysis that it is definitely not feasible. Session uses SessionID to differentiate users. Generally, SessionID cannot be duplicated. That is to say, Session generally does not have a "serial number. Since the SessionID of the current user is appended to the page each time it is submitted, the Session should be cross-page, that is, all the pages of a website use the same Session. You can do a test by yourself. Ask the reader to open the page just now, press Ctrl + N to open the second page, and then click "Write Session" in the first page, click the "read Session" button on the second page to check that the Session value is correctly read. The answer to the third question is correct.

· Range of Session Status: use the same client (Browser instance) to access all pages of the same application.

Let's do another experiment to check the capacity of the Session. before the test, modify Web. config and set the Session to the StateServer mode. Then, modify the code written to the Session to the following (do not forget using System. Data. SqlCient ):

The Code is as follows: Copy code

DataSet ds = new DataSet ();

Using (SqlConnection conn = new SqlConnection (@ "server = (local) SQLEXPRESS; database = Forum;

Trusted_Connection = True "))

{

SqlDataAdapter da = new SqlDataAdapter ("select * from tbUser; select * from tbBoard;

Select * from tbTopic; ", conn );

Da. Fill (ds );

}

ArrayList al = new ArrayList ();

For (int I = 0; I <10000000; I ++)

Al. Add (ds );

Session ["LargeData"] = al;

We add DataSet containing three tables to the ArrayList for 10 million times. Since these tables have only a few records in almost each table, this can simulate a large amount of data. On the startup page, click the "Write Session" button and you will find that Windows service processes all occupy up to 70 MB of memory, as shown in 12-9.

 

Figure 12-9 store a large amount of data in the Session

Session is independent of websites and users. If there are two websites on the server, each of which has 100 online users, the memory will be 14 GB. Is it a terrible number? Therefore, although there is no limit on the size of the Session, we must never abuse the Session. I recommend that you store less than KB of data in the Session.

· If you use the InProc mode Session, storing too much data will cause the IIS process to be recycled and the Session will be continuously lost.

· If you use StateServer to store sessions, data must be serialized before being stored in sessions. serialization consumes a lot of CPU resources.

· If you use sessions in SqlServer mode, data must be serialized and stored on disks, but not suitable for storing a large amount of data.

12.3.6 Session Lifecycle
After learning that the data stored in the Session has no size limit, we may have to pay more attention to the Session lifecycle. We already know that the Session was created when the user visited the website for the first time. When did the Session be destroyed? Session uses a smooth timeout technique to control when to destroy a Session. By default, the Session Timeout value (Timeout) is 20 minutes. If you do not visit the website for 20 consecutive minutes, the Session is withdrawn, if the user visits the page again within the past 20 minutes, the time will be timed again in 20 minutes. That is to say, the time-out period is the time-out period of continuous access, instead of 20 minutes after the first visit. You can also modify the timeout value by adjusting the Web. config file:


Of course, you can also set it in the program:

Session. Timeout = "30 ";

Once the Session times out, data in the Session will be recycled. If you use the Session system again, a new SessionID will be assigned to you. This section describes how to store SessionID in a URL. Configure the Web. config file and set the Session Timeout time to 1 minute. SessionID is stored in the URl. Open the page and click the "Write Session" button. click the button again in one minute and check whether the SessionID changes.


As shown in 12-10, SessionID does change.

 

 

Figure 12-10 SessionID changes after timeout

However, do not trust the Timeout attribute of the Session. If you set it to 24 hours, it is hard to believe that the user's Session is still there after 24 hours. Whether a Session exists depends not only on the Timeout attribute, but may cause Session loss in any of the following cases (the so-called loss is that the original Session is invalid before the Timeout ).

· Files in the bin directory are rewritten. Asp.net has a mechanism. To ensure that the system runs normally after the dll is re-compiled, it restarts a website process, which will cause Session loss. Therefore, if an access database is located in the bin directory, or if other files are modified by the system, the Session will be lost.

· SessionID is lost or invalid. If you store SessionID in the URL but use absolute address redirection, The SessionID in the URL will be lost, and the original Session will become invalid. If you store SessionID in the Cookie, the client disables the Cookie or the Cookie reaches the Cookie quantity limit in IE (20 for each domain), and the Session will be invalid.

· If InProc Session is used, the Session will be lost when IIS is restarted. Similarly, if the Session of StateServer is used, the server will also lose the chance to restart the Session.

In general, if Session is stored in IIS and the Timeout settings of the Session are relatively long, and a large amount of data is stored in the Session, it is very easy to cause Session loss.

Finally, how is Session Security? We know that only SessionID in the Session is stored on the client, and HTTP hair is added to the server each time the page is submitted. SessionID is only an identifier and has no content. The actual content is stored on the server. In general, the security is acceptable, but I suggest you do not use cookieless and SqlServer mode sessions. Exposing the SessionID to the URL and storing the content in the database may cause potential attacks.

12.3.7 traverse and destroy sessions
Although the Session is very convenient, you need to constantly practice the Session to make good use of the Session, according to the characteristics of your website, flexible use of various modes of Session. I would like to add two additional points for accessing the Session using a program.

· How to traverse the current Session set.

The Code is as follows: Copy code

System. Collections. IEnumerator SessionEnum = Session. Keys. GetEnumerator ();

While (SessionEnum. MoveNext ())

{

Response. Write (Session [SessionEnum. Current. ToString ()]. ToString () +"
");

}

For our example, the output is the same as that of Figure 12-1. If you only want to monitor sessions, you can also obtain detailed information through trace. Add:


Open the page and click "Write Session". The page displays 12-11.

 

Figure 12-11 use trace to observe the session Status

· How to immediately invalidate a Session. For example, after you exit the system, all the data stored in the Session is invalid. You can use the following code to invalidate the Session.

Session. Abandon ();

12.3.8 Session FAQs and summary
The basic knowledge of the Session is introduced here. Now let's look back at the several questions in section 1. Can you answer them all? To enhance the concept, I made a comparison between the three Session modes (assuming that all Session IDs are stored using cookies ).

Table 12.1 Session comparison of three modes


InProc
StateServer
SQLServer
 
Storage physical location
IIS process (memory)
Windows service process (memory)
SQLServer database (Disk)
 
Storage type restrictions
Unlimited
Serializable types
Serializable types
 
Storage size limit
Unlimited
 
Scope of use
The current request context, which is independent of each user
 
Lifecycle
The first time you access the website, the created Session times out and is destroyed.
 
Advantages
High Performance
Sessions are not dependent on Web servers and are not easy to lose
 
Disadvantages
Easy to lose
Serialization and deserialization consume CPU resources
Serialization and deserialization consume CPU resources and slow Session reading from disk
 
Usage principles
Do not store large amounts of data
 

You may encounter many strange problems when using the Session. Before the end of this section, I have listed several common FAQs for your reference:

· Why are the sessionids of each request different?

N may be caused by not saving any information in the Session, that is, the Session is not used anywhere in the program. The Session will be associated with the browser only after the content is saved in the Session, and the SessionID will not change at this time.

· Why Will Session be lost when cookieless is set to true?

N when cookieless is used, you must replace the absolute path in the program with the relative path. If the absolute path is used, ASP. NET cannot save the SessionID in the URL.

· Is there a way to know how much memory the application Session occupies during running?

N there is no way. You can estimate it by checking the IIS process (InProc mode) or aspnet_state process (StateServer mode.

· Is it possible to know the list of users who use Session for the entire website?

N is difficult for InProc mode and StateServer mode. For SqlServer mode, you can query tables that store sessions and try it.

· When frameset is set in the page, it is found that the SessionID of the page displayed in each frame is different in the first request. Why?

N is because your frameset is placed on an HTML page rather than An ASPX page. In general, if the frameset Is An aspx page, When you request a page, it first sends the request to the Web server. At this time, the SessionID is obtained, then the browser requests other pages in the Frame respectively, so that the sessionids of all pages are the same, that is, the SessionID of the FrameSet page. However, if you use an HTML page as a FrameSet page, the first request will be an HTML page. When the page is returned from the server, no Session is generated, then the browser will request the pages in the Frame. In this way, these pages will generate their own SessionID, so this problem may occur in this case. When you refresh the page, SessionID will be the same, and it is the SessionID of the last request page.

ASP. NET Session 7


One of ASP. NET sessions
For value-type variables, the Session stores copies of the value type.

The Code is as follows: Copy code
Session ["_ test0"] = 1;
Int I = (int) Session ["_ test0"] + 1;
Int j = (int) Session ["_ test0"];

Result I = 2, j = 1

ASP. NET Session 7 Knowledge 2
For new variables of the reference class, the reference is saved in the Session.

The Code is as follows: Copy code

CDACommon cda = new CDACommon ();
Session ["_ test"] = cda. GetDataSet ("select top 1 * from tb_customer ");
DataSet ds = (DataSet) Session ["_ test"];
DataSet ds2 = (DataSet) Session ["_ test"];
Ds. Tables [0]. Rows [0] [0] = "9999 ";
Result ds. Tables [0]. Rows [0] [0] = "9999" ds2.Tables [0]. Rows [0] [0] = "9999 ";

ASP. NET Session 7
Session cycle

After the new browser window is started, a new Session is started to trigger the Global Session_Start call. The new Session is not started in the browser window opened in the first browser window. After the Session expires, the execution page commit will also trigger Session_Start, which is equivalent to a new Session.

ASP. NET Session
Call Session

For Web Services, each method call starts a Session. You can use the following method to make multiple calls in the same Session.

CWSSyscfg cwsCfg = new CWSSyscfg ();
CwsCfg. CookieContainer = new System. Net. CookieContainer ();
CWSSyscfg is a Web Service class. The CookieContainer attribute is set for the proxy class by the Web Service. As long as the CookieContainer attribute of multiple proxies is the same value, the Web Service is called in the same Session. It can be implemented in singleton mode.

ASP. NET Session 7: 5
Session Data Validity Period

As long as the page has a submitted activity, all items of the Session will be maintained, and the Session will expire if the page does not submit any activity within 20 minutes (default configuration. Multiple Data items stored in the Session are invalid as a whole.

ASP. NET Session 7: 6
Session Storage

If a non-serialized class such as DataView is saved in a Session, it cannot be used in the Session saving mode using SQLServer. To check whether a class is serialized, you need to check whether the class is marked with [Serializable.

Seven-Point introduction to ASP. NET sessions
About Sessuon cleanup

If I keep a relatively large datasetin session, the memory occupied by aspnet_wp.exe will be very large. If I quit the page using this DataSet, I want to release this Session, and I will use the Session. clear () or DataSet. clear () cannot reduce memory usage even if the Session expires.

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.