Asp. NET how to use the session correctly

Source: Internet
Author: User
Tags iis administration

The session object is used to store the information that is required for a particular user session from the beginning of a user's access to a particular ASPX page, until the user leaves. The variables of the session object are not cleared when the user switches the application's page.
For a Web application, the content of the Application object accessed by all users is exactly the same, while the content of the session object accessed by different user sessions varies. Session can save the variable, which can only be used by one user, that is, each Web browser has its own session object variable, that is, the session object is unique.

What is a session?

The web is stateless, and he provides a new way to render a new page every time a user submits a request to the server. As is known to all, HTTP is a stateless protocol that he cannot keep connected through the page and the client. If the user needs to add some information and jump to another page, the original data will be lost and the user will not be able to recover the information. What do we need this thing for? We need to save the information! Session provides a scenario for saving information on the server side. He can support any type of object and user object information to be saved as an object. The session is saved independently for each client, which means that the session data stores the underlying information for each client. Please see:

Each client has a separate session.

State management with session is one of the best features of ASP. Because it is secure, transparent to clients, and capable of storing objects of any type. In addition to these advantages, sometimes the session can lead to performance issues for sites with higher performance requirements. Because he consumes the server's memory to store the data users need to access the site, let's take a look at the pros and cons of the session for your Web app.

The pros and cons of Session

Next we discuss the pros and cons of using the session under normal circumstances, and I'll describe the context in which each session is used.

Advantages:

He can help maintain user status and data throughout the application.

He allows us to simply implement storing objects of any type.

Save the client data independently.

For the user, the session is secure and transparent.

Disadvantages:

Because the session uses the server's memory, it becomes a performance bottleneck when the user volume is large.

He also becomes a performance bottleneck during serialization and deserialization, because we need to serialize and deserialize the data we store in the StateServer (State Service) mode and in SQL Server mode.

In addition, the various models of the session have their pros and cons. Next we will discuss the various session modes.

Read/write to session

Reading/Writing the session is very simple, just like using ViewState, We can use the System.Web.SessionState.HttpSessionState class to interact with the session, which is built (provided) within the ASP. The following code is an example of storing using the session:

Storing UserName in sessionsession["UserName"] = Txtuser.text;

Now let's look at how to read the data from the session:

Check weather Session variable null or Notif (session["UserName"]! = null) {    //retrieving UserName from session    L Blwelcome.text = "Welcome:" + session["UserName"];} else{//do Something Else}

We can also store other objects, and the following example shows how to store a DataSet into a session

Storing DataSet on sessionsession["DataSet"] = _objdataset;

The following code shows how to read a DataSet from within a session

Check weather Session variable null or Notif (session["DataSet"]! = null) {    //retrieving UserName from session    Da Taset _myds = (DataSet) session["DataSet"];} else{    //do Something Else}

Reference documents:

MSDN (Read the session variable section)

Session ID

Asp. NET uses a 120bit identifier to identify each session. This is a sufficiently safe, irreversible design. When the client and the server are communicating, the session ID needs to be transmitted between them when the client sends the request data, ASP. NET Search session ID, retrieve data through session ID. This process is done through the following steps:

Client-side Click Site-client information is stored by session

The server creates a unique session ID for the client and stores the ID on the server side.

The client obtains the information saved on the server by sending a request with SessionID

The server side obtains the serialized data from the State service through session provider and casts the type to the object

The following is a picture of the process:

Communication of client, Web server, Session provider

Reference documents:

SessionID in MSDN

Session Mode and Session Provider

The following session modes are available in ASP.

InProc

StateServer

Sql server

Custom

Each session state has a session Provider. The following graphs will show their relationship:

Session State system diagram

We can choose between these basic session state provider. When ASP. NET receives a request for information with the session ID, the session state and his corresponding provider are responsible for providing and storing the corresponding information. The following table shows the session mode and the name of the provider:

Session State mode State Provider
InProc In-memory object (built-in objects)
StateServer Aspnet_state.exe
Sql server SQL Server Database
Custom Custom Provider

In addition, there is another mode: "OFF", if we choose this option, the session will not be able to provide services for this application. But our goal is to use the session, so we will discuss the above four session modes.

Session states

The session state mode basically thinks that all the session configuration and maintenance are given to the Web application. Session state He is a big thing in itself, and he basically means all of your configuration for the session, whether it is the Web. config or the page back-end code. The element is used as the session configuration in Web. config. The elements can be configured with mode (mode), timeout (timeout), stateConnectionString (State connection string), CustomProvider (custom provider), and so on. We've already discussed the connection string for each section. Before we discuss session mode, let's briefly summarize some of the following session events:

Session Event

There are two session events that can be used in asp:

Session_Start

Session_End

You can handle both of these events in the application Global.asax this file, the Session_Start event is triggered when a new session is opened, and Session_End is triggered when the session is recycled or expires:

void Session_Start (object sender, EventArgs e) {    //Code that runs if a new Session is started} void Session_End (obj ECT sender, EventArgs e) {    //Code that runs when a session ends.}

Reference documents:

Application and Session Events

Session mode

We've talked about session mode, and then we'll talk about the different patterns:

Off

InProc

StateServer

Sql server

Custom

If we set the session mode= "off" within Web. config, the session will not be available in the app, and his settings are:

InProc Session Mode:

This is the default session mode for ASP., which stores session information in the current application domain. This is the best-performing session mode. But his biggest drawback is that the session data will be lost when we restart the service. The InProc pattern has some pros and cons, and we'll detail these points next.

InProc Overview:

As we have said, the InProc mode session data will be stored in the current application domain, so he is the simplest, fastest, and easy to use.

InProc mode session data is saved in a collection object within the application domain, he works in an application pool, and if we restart the service, we lose the session data. Normally the client sends the request, state provider reads the data from the memory object and returns it to the client, and in Web. config we must provide session mode and set expiration time:

In the settings above, the session expiration time is set to 30 minutes, which can also be configured from the background code.

session.timeout=30;

There are two Session events that can be used in asp: Session_Start () and Session_End () and this mode (back-end code control) only supports the Session_End () event. This event is called during the session timeout, typically InProc session mode:

The Session_End () event is called when the session expires. InProc is a very fast processing mechanism because there is no serialized read/write process, and the data is stored in the same domain.

When do we use InProc mode?

InProc is the default session mode, and he is very suitable for small applications and smaller users, and we should try to avoid using him in the context of Web garden and Web farm (in the future I will talk about this scenario)

Advantages and Disadvantages

Advantages:

He stores session data in the current application domain, so accessing the data can be very fast, simple, and efficient.

You do not need to serialize the storage of objects in InProc mode.

It's very simple to use, just like viewstate.

Disadvantages:

Although InProc is the fastest, most versatile, and default mechanism, he has a number of limitations:

If the working application process is recycled, the session data will all be lost.

Although he is the fastest, but when the session data is too large and too many users, he will affect the performance of the entire program due to the large amount of memory usage.

We cannot use this pattern in a Web garden environment.

This mode is not suitable for Web farm (Web farms) environments.

Now, let's look at other available methods to circumvent these drawbacks, first of all the StateServer mode:

StateServer Session Mode

StateServer Mode Overview

This is also called Out-proc session mode. StateServer uses a standalone Windows service to provide session services that are independent of IIS and can use a single server. StateServer services are available from Aspnet_state.exe. This service can also run on the same server as your application service, noting that he is a service independent of the Web application domain. This means that the session data still exists after you restart your Web service. The disadvantage of this scenario is that there is a performance bottleneck: Data read and write needs to be serialized and deserialized, because it is not the same application domain, so he also increases the performance consumption of data read and write because they are two different processes.

Configuring StateServer Session Mode

In StateServer mode, session data is stored in a service that is independent of IIS. This process runs as a Windows service and you can start it in the Windows Service Manager (MMC) or the command line.

By default, the ASP. NET StateServer (Chinese name: ASP. NET State Service) is started by default by "manual" and we have to set him to automatic.

If you start from the command line only need to enter: "net start aspnet_state"; By default, this service listens on TCP port 42424, but we can change this setting in the registry.

Right now Let's take a look at the Web. config setting for StateServer, in StateServer settings we need to specify the StateServer connection string stateconnectionstring: Point to the system running StateServer. By default, stateConnectionString uses the IP127.0.0.1 (localhost) port to use 42424.

When we use StateServer, we can also set the timeout statenetworktimeout attribute to specify the number of seconds to wait for the service response, that is, the event interval that makes the request to the cancellation response. By default, it is 10 seconds.

When storing with StateServer, the object will be serialized for storage, and when the object is read, the data will be deserialized, let's take a look at the following example:

How the StateServer works

We use StateServer to avoid unnecessary session data loss when restarting the Web service. StateServer is maintained in the Aspnet_state.exe process as a service, and the process maintains all session data, but we need to serialize the data before it is stored in the StateServer.

As shown, the client sends the request to the Web server, the Web server stores the session data in StateServer, StateServer may be in the current system, or in another system, but he must be independent of IIS, in order to achieve him, We have to configure stateconnectionstring in Web. config. For example, we set the point to 127.0.0.1:42424, which will store the data in the local system, for the purpose of changing the stateserver point, we change the IP and determine the aspnet_ The state.exe runs normally on this system, and then when you need to read and write the session (that is, by modifying the IP to cause a wrong point), you will throw an exception like this:

When we store an object into the session, the object is serialized. The system uses the state provider to store the data in StateServer. When the data is read, the state provider returns the data, with the complete flowchart such as:

StateServer Session Mode Example:

This is a simple example of using the StateServer session pattern, which I created directly in IIS to easily understand his usage:

Step 1: Open the Visual studio> file > New > website. Select HTTP as the location for your web app.

Now that you open IIS, you will see that you have created a virtual directory whose name is your app name, which in my case is stateserver.

Step 2: Create a simple UI: he will get a student's role number and name, and we will save the name and number to the StateServer session. I will also create a class: Studentinfo, this class is defined as follows:

[Serializable]public class studentinfo{    //default Constructor public    studentinfo ()    {           }//    /    //Create object of student    Class    //////int rollnumber///string Name public    studentinfo (Int Introll, String strName)    {this        . Roll = Introll;        This. Name = StrName;    }     private int introll;    private string StrName;    public int Roll    {        get        {            return introll;        }        Set        {            introll = value;        }    }     public string Name    {        get        {            return strName;        }        Set        {            strName = value;}}    }

Now look at the backend code, I added two buttons: One is to save the session, and the other is to get the session:

protected void btnSubmit_Click (object sender, EventArgs e) {    studentinfo _objstudentinfo =       new Studentinfo ( Int32.Parse (Txtroll.text), txtusername.text);    session["Objstudentinfo"] = _objstudentinfo;    Resetfield ();} protected void Btnrestore_click (object sender, EventArgs e) {    studentinfo _objstudentinfo = (studentinfo) session[" Objstudentinfo "];    Txtroll.text = _objstudentinfo.roll.tostring ();    txtUsername.Text = _objstudentinfo.name;}

Step 3: Configure the StateServer of your web. config, as described earlier, make sure that Web. config is in a state that is on and running on the server that the configuration points to.

Step 4: Run the app.

Enter data and click Submit.

Next Test, I'll explain in full how to use StateServer

First: Remove the Studentinfo class [Serializable] attribute, and then run the app. When you click the Submit button, you will see the following error:

It is clear that you must serialize your objects before storing them.

Second: Run the program, after you click the Submit button to save the data, restart IIS

If in InProc, I guarantee that your session data will be lost, but in StateServer, click the Restore Session button, you will get your original data, because StateServer data does not depend on IIS, it saves data independently.

Third: Stop the StateServer service in the Windows Service Management Program (MMC), and then click the Submit button, and you will see the following error:

Because your stateserver process is not running, keep these three points in mind when you use StateServer.

Pros and cons

Based on the above discussion:

Advantages:

StateServer is run independently of IIS, so no matter what the problem with IIS affects StateServer data.

He can be used in Web farm and Web garden environments.

Disadvantages:

To serialize and deserialize, slow down the speed.

StateServer need to ensure normal operation.

I'm here to stop StateServer's storytelling, and you'll see him in load balancer more and more interesting points in the Web farm,web garden context.

Reference documents:

State Server Session Mode

ASP. NET Session State

SQL Server Session Mode

Introduction to SQL Server mode

Asp. NET This session mode provides us with more security and reliability, in this mode, session data is serialized and stored in a SQL Server database, The disadvantage of this pattern is that the session needs to serialize and deserialize the read and write mode become the main performance bottleneck, he is the best choice for Web farm.

To set up SQL Server, we need these SQL scripts:

Installation: InstallSqlState.sql

Uninstall: UninstallSqlState.sql

The simplest way to configure this is to use the Aspnet_regsql command.

Previously explained how to configure, this is the most useful state management method in Web farm mode.

Why do we use SQL Server mode?

SQL Server Session mode provides a more secure and reliable session management.

He ensured that the data was in a centralized environment (database).

SQL Server mode should be used when we need to implement the session more securely.

This is a perfect solution if the server often needs to be restarted.

This is a perfect solution to the Web farm and Web garden (which I will explain in detail later).

We need to use SQL Server mode when we need to share a session between two applications.

Configuring SQL Server Session Mode

In SQL Server mode, our data is stored in SQL Server, so we first have to provide the database connection string in Web. config, sqlconnectionstring is used to do this.

After the connection string configuration is complete, we will configure SQL Server, where I will demonstrate how to configure the database with the Aspnet_regsql command.

First step: Go to the command line and go to the framework version directory e.g. : C:\windows\microsoft.net\framework\.

The second step is to run the aspnet_regsql command with the parameter.

Here is the use of parameters:

Parameters Description
-ssadd Add SQL Server mode session state.
-sstype P P persistence. Persist this data in a database
-S Server name
-U User name
-P Password.

After the run is finished, you see the following information:

Configuration ends.

Step Three:

Open SQL Server and view the database ASPState library, there will be two tables:

Aspstatetempapplications

ASPStateTempSessions

Change the connection string in the settings to create an application like the one in the StateServer example

Click Submit to save roll number and user name, open the database, enter the ASPStateTempSessions table, this is your saved session data:

Now let's discuss some of the issues discussed in the following StateServer models:

1. Remove the serialize feature from the Stydentinfo class (keyword)

2. Restart IIS and then read session data

3. Stop the SQL Server service

I think I have explained these questions very clearly in stateserver.

(Note: The first will result in the inability to serialize the object, throws an exception, the second has no effect, and the third, when the database service is closed, will have an impact, and restarting the database service will retrieve the data in the session, because he is persistent storage.) )

Advantages and Disadvantages

Advantages:

Session data is not affected by IIS restart

The most reliable and secure session management model

He stores session data locally, enabling other applications to easily access

Very useful in Web Farm and Web garden scenarios

Disadvantages:

Compared to the default mode, it will appear very slow.

Serialization and deserialization of objects can be a performance bottleneck

Because SQL Server needs to be accessed on different servers, we must ensure the stable operation of SQL Server.

Resources:

Read more about SQL Server mode

customizing session Mode

Typically, we use InProc mode, StateServer mode, and SQL Server mode, but we still need to understand some of the user-defined session patterns. This is a very interesting session mode, because the user's session is all left to us to control, even the session ID, you can write the algorithm to generate the session ID.

You can easily develop custom provider from the base class Sessionstatestoreproviderbase, and you can also generate SessionID by implementing Isessionidmanager interfaces.

is the process of customizing the method:

In the Initialize method, we can set a custom provider. He will provide an initial connection to the provider. Setitemexpirecallback is used to provide sessiontimeout (session expiration) and we can register a method to invoke when the session expires. InitializeRequest is called when the request is initiated and Createnewstoredata is called when creating an instance of the SessionStateStoreData (session data storage Class).

When do we use the custom session mode?

1. When we want to store session data in a database other than SQL Server.

2. When we have to use an existing (specific) table to store session data.

3. When we need to use a custom SessionID

How do I configure a custom session mode?

We need to make this configuration in Web. config:

If you want to learn more about custom patterns, please refer to the Resources section.

Advantages and Disadvantages

Advantages:

1, we can use an existing table (the specified table) to store session data. This is useful when we are using a previously used database.

2. He runs independently of IIS, so restarting the server does not affect him either.

3. We can create our own session ID logic to assign session ID.

Disadvantages:

1, processing data is very slow.

2. Create a custom session state provider is a basic (low-level) task that requires careful handling of situations and data security.

I recommend that you use the provider provided by a third party instead of writing a set of provider yourself.

Resources:

Custom Mode

Overview of Production Deployment:

Deploying our applications in a real production environment is a significant challenge for a web developer. Because in a large production environment, there is a large number of user data to be processed, the amount of data large to a server is difficult to load such a huge amount of data processing. This concept comes from the use of Web farm,web garden, load balancing.

A few months ago, I deployed a real-world environment: This environment handles millions user access and over 10 domain controllers, with load balancing carrying more than 10 servers and service databases. such as the trading server, LCS server. The biggest challenge comes from session management across multiple servers. A simple graph is shown for this production environment:

I'll try to explain and let you remember the different scenarios.

Application Pools

This is one of the most important things when you create a real production environment. Application pools are applications that are used in IIS to separate different worker processes, and application pools can separate our applications to provide better security, reliability, and effectiveness. Application pools are applied on the server when one process is having problems, or other processes are not affected when they are reclaimed.

Role of application pool:

The configuration role of the application pool is an important security measure in IIS6 and IIS7. Because when the application accesses the resource, he specifies the identity of the application. In IIS7, there are three predefined ways of identity designation, which is the same as IIS6.

Application Pool Role Describe
LocalSystem An account built in to manage permissions on the server. He can access local and remote resources. Any server files or resources, we must set the identity of the application to LocalSystem.
Localservices Built-in local authentication. He cannot make any network access.
NetworkServices This is the default identity for the application pool, and NetworkServices is an authenticated local user account right.

Establish and specify an application pool

Open the IIS Administration page, right-click the application pool directory, new

Give the application pool an ID and click OK.

Now, right-click a virtual directory (the StateServer site I'm using) to assign Stateserverapppool to the StateServer virtual directory.

Now this StateServer site is running in a specified standalone application pool, Stateserverapppool. No other application will affect this program. This is the main benefit of a standalone application pool.

Web Garden

By default, each application pool runs in a separate worker process (W3Wp.exe). We can assign multiple processes to a single application pool, one application pool to run multiple processes, and this is called Web Garden (Web Park), and multiple worker processes a single application can have better output performance and less time in many cases. Each worker process will have its own thread and memory space.

As shown in IIS, there will be multiple application pools and at least one worker process per application pool, and a Web garden will have multiple worker processes.

In your application, the use of the Web Park will inevitably result in a restriction: if we use InProc mode, our application will not work correctly because the session will work in different processes. To avoid this problem, we will use the out-of-process (OURPROC) session mode, which we can use either state Server or SQL Server session mode.

Key Benefits:

The worker processes in the Web garden share requests for each process, and if one process hangs, the other processes work and continue processing requests.

How to build a Web garden?

Right-click the program pool->performance (performance?). ) tab, select Web Garden (Web Park) Section

By default he has a value of 1, and now he changes to a number larger than 1.

How do I specify a session within the Web Park?

I have explained that the inproc pattern is handled in a single worker process, storing objects in-process, and now, if we are dealing with multiple processes, session processing will become difficult because each worker process has its own memory. So if the first request data to WP1 and save the session data, the second request to the WP2 I will not be able to correctly obtain the session data, the value will throw an exception. Therefore, please avoid using InProc mode in Web garden mode.

We use the StateServer or SQL Server mode to handle this situation, as explained before, these two patterns do not depend on the work process, in the previous example also said that when the IIS restart you can still access the session data.

Session mode is recommended
InProc No
StateServer Yes
Sql server Yes

Web Farm and load balancing

This is the most common scenario in a production environment, when you need to deploy your app on multiple servers, the main reason for using this mode is that we want to load balance across multiple servers, and a load balancer is used to distribute the load to multiple servers.

We see that when a client sends a request through a URL to a load balancer and then distributes the request to the server through a load balancer, the load balancer makes the requested distribution between the different servers.

Now what do we do with our session?

Processing session in Web farm and load balancing

Dealing with a session in a Web farm is a challenging task.

Inproc:inproc session mode, session data is stored as objects in the worker process, each server will have his own worker process and will keep session data in memory.

If a server is down, the request will be accessed by other servers, and no corresponding session data exists in the other servers. Therefore, the use of InProc mode is not recommended in Web farm scenarios.

State Server: Previously explained how to use and configure StateServer mode, you will know how important he is in webfarm environment, because all session data will be stored in one place.

Remember, in a Web farm environment, you have to make sure that you have the same section on all your Web servers, that the other configurations are consistent with the previous descriptions, that all Web. config files have the same configuration properties (stateConnectionString) in session In the state.

SQL Server: This is another option, which is also the best choice in the Web farm environment, we first need to configure the database, the next steps have been said before.

As shown, all Web server session data will be stored in a SQL Server database. Keep in mind that you will store objects in both StateServer mode and SQL Server mode. When a Web server is hung up, the load balancer will distribute the request to other servers and he will be able to retrieve the session data from the database because all session data is stored in the database.

In short, we can use StateServer and SQL Server mode to deploy the Web farm, and we need to avoid using InProc mode as much as possible.

Session and Cookie

The client uses cookies in conjunction with the session, because the client needs to provide the appropriate session ID for each request, and we can use the following methods:

Using cookies

Asp. NET uses a specific cookie called: Asp.net_sessionid this is provided automatically when the session collection is created, which is the default setting and the session ID is transmitted via a cookie.

Cookie munging

When the user sends a request to the server, the server decodes the session ID and adds him to the link for each page when the user clicks on the link, ASP. NET encodes the session ID and transmits it to the page requested by the user, and now the requested page can get the session variable. This is done automatically when ASP. NET discovers that the user's browser does not support cookies.

How to implement a cookie munging

For this, we must ensure that our session state is cookie-less.

Remove session

The following method is used to remove the session

Method Describe
Session.remove (Strsessionname) Remove an item from the session state
Session.removeall () Remove all items from the session collection
Session.clear () Removes all items from the session collection. Note:clear and Removeall.removeall () no difference clear () is internal.
Session.Abandon () Cancels the current session.

Enable and disable session

In terms of performance optimization, we can enable or disable the session because each page reads and writes a session with some performance overhead, so it's more appropriate to enable or disable the session instead of using his default configuration: Always. We can enable and disable the session in two ways:

Page level

Application-level

Page level

We can disable the session in the EnableSessionState property of the page directive

Similarly, we can make him read-only, which will allow access only to the session and prohibit the writing of the message to the session.

Application-level

By setting the properties of the Web. config EnableSessionState you can have the session disabled throughout the application.

In general, we are using page-level restrictions, so that you can flexibly control the use of the session.

Reference documents:

How to Disable ASP. NET Session State

Summarize

Hopefully you'll be more familiar with the session now, how to use the session, and how to use it in Web farm, as summarized below:

1, InProc Session provider is the fastest, because all the data exist in the application's memory, the Session data in the IIS restart, or the site is recycled, you can use this mode on the smaller users, but do not use under the Web farm.

2. State Server Mode: Session data is stored in aspnet_ In the State.exe application, he saves session data outside of the Web service, so a problem with the Web service does not affect his session data, which needs to be serialized before the session data is stored in the StateServer, in the Web We can safely use this pattern in farm.

3. SQL Server Mode: He saves the session data to SQL Server, we need to provide a connection string, we also need to serialize the object when stored, this mode is very useful in the production environment of the actual Web farm.

4, we can also use the custom mode, when we need to use an existing table to store session data, in the custom mode, we can also create a custom session ID, but do not recommend yourself to implement provider, we recommend the use of third-party provider.

Hope you can like this article, I hope you can give me valuable advice to help everyone to improve together, thank you again for your reading.

NOTE: Reprint http://www.cr173.com/html/24780_1.html

Asp. NET how to use the session correctly

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.