Session use __.net in asp.net

Source: Internet
Author: User
Tags session id sessions
Introduction to the session model

What is the session? In short, the server gives the client a number. When a WWW server is running, there may be several users browsing the Web site that is being shipped on this server. When each user first connects to the WWW server, he establishes a session with the server, and the server automatically assigns a SessionID to identify the user's unique identity. This SessionID is a 24-character string randomly generated by the WWW server, and we'll see what it looks like in the following experiment.

The only SessionID is of great practical significance. When a user submits a form, the browser automatically attaches the user's SessionID to the HTTP header (which is the automatic function of the browser and is not detected by the user) and returns the result to the corresponding user of the SessionID when the server finishes processing the form. Imagine, if there is no SessionID, when two users register at the same time, how the server can know exactly which user submitted which form. Of course, SessionID has a lot of other functions that we'll mention later.

In addition to SessionID, there is a lot of additional information in each session. But for the program to write ASP or asp.net, the most useful thing is to access asp/asp. NET, which stores individual information for each user. For example, we would like to know if the users visiting our site have browsed through several pages, and we may include them in each page that the user may visit:

<%
If session ("pageviewed") = "" Then
Session ("pageviewed") = 1
Else
Session ("pageviewed") = Session ("pageviewed") + 1
End If
%>

The following sentence lets users know that they have browsed through several pages:

<%
Response.Write ("have viewed" & Session ("Pageviewed") & "pages")
%>

Some readers may ask: This looks like an array of sessions ("...") Where it came from. Do I have to define it. In fact, this session object is the built-in object of the WWW server with ASP interpretation capabilities. That is, the ASP's system has given you the definition of this object, you only need to use on the line. where session ("..") In the ... Just like the variable name, session ("...") The $$$ in the =$$$ is the value of the variable. You just have to write a sentence and you can access it on every page of the user. The value in the variable.

In fact, the ASP built a total of 7 objects, there are sessions, application, cookies, Response, Request, server and so on. There are similar objects in other server-side scripting languages, such as JSP, PHP, and so on, but not in the same way as they are called or used. the drawbacks of ASP session functionality

At present, ASP's developers are using the session this powerful feature, but in their use of the process has found that the ASP session has the following defects: Process dependencies: ASP sessions State in the process of IIS, that is, inetinfo.exe this program. So when the Inetinfo.exe process crashes, the information is lost. In addition, the restart or shutdown of the IIS service can result in loss of information. Limitations of Session state usage: When a user accesses another Web site from a Web site, the sessions information is not migrated over. For example: Sina Web site's www server may be more than one, a user login to go to each channel to browse, but each channel on a different server, if you want to share session information in these WWW server how to do? Cookie dependencies: In fact, the client's session information is stored in the cookie, and if the client completely disables the cookie function, he will not be able to enjoy the function provided by the session.

In view of the above defects of ASP session, the designers of Microsoft have made corresponding improvement in the design and development of ASP.net session, completely overcome the above defects, make asp.net session become a more powerful function. Introduction to Web.config files

Some asp.net programmers say: web.config files. I have never heard of Ah, but I write the program can not be very normal operation. Yes, you're right, there's no Web.config. File programs can run normally. However, if you do a large web site, you need to do some overall configuration of the site, such as the entire Web page in what language to write, the site's security authentication mode, session information storage mode, etc., then you need to use the Web.config file. Although some of the options in the Web.config file can be configured through IIS, the configuration in IIS is overwritten if the appropriate settings are in Web.config. Also, the biggest convenience of web.config files is that you can access the settings in Web.config by calling the System.Web namespace in the ASP.net page.

There are two types of web.config, the server configuration file and the Web application configuration file, each named Web.config. In this configuration file, a series of information about which language is used in the current IIS server, the application Security authentication mode, and the session information storage mode are saved. This information is saved using XML syntax, and if you want to edit it, use a text editor.

Where the server configuration file works for all applications in all sites under the IIS server. In the. NET Framework 1.0, the server's Web.config file is present in:/winnt/microsoft.net/framework/v1.0.3705.

The Web application configuration file, web.config, is saved in each Web application. For example, the root directory for the current Web site is/inetpub/wwwroot, and the current Web application is MyApplication, the Web application root should be:/inetpub/wwwroot/myapplication. If your site has only one Web application, the application's root directory is generally/inetpub/wwwroot. If you want to add a Web application, you can add a virtual directory with the starting point of the application in IIS. The files and directories in this directory will be treated as a Web application. However, adding a Web application through IIS does not generate Web.config files for you. If you want to create a Web application with a Web.config file, you need to use Visual Studio.NET to build a new Web application project.

The configuration file for the Web application web.config is optional and dispensable. If not, each Web application uses the server's Web.config configuration file. If it does, the corresponding values in the server Web.config configuration file are overwritten.

In ASP.net, web.config modifications are saved automatically and immediately, without the need to restart the Web application before the configuration file changes in the ASP. Session configuration information in the Web.config file

After opening the configuration file for an application web.config, we will find the following paragraph:

<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "20"
/>

This section is about configuring how the application stores session information. The following operations are mainly for this section of configuration. Let's take a look at what this section of the configuration contains. The syntax for the sessionstate node is this:

<sessionstate mode= "off| inproc| stateserver| SQL Server "
              cookieless=" True|false "
              Timeout=" Number of minutes "
              stateconnectionstring= "Tcpip=server:port"
              sqlconnectionstring= "SQL connection String "
              statenetworktimeout=" number of seconds "
/>

The attributes that must exist are

Property Options Describe
Mode setting where to store session information
Off Set to do not use the session feature
InProc Set to store session in-process, which is the storage mode in ASP, which is the default value.
StateServer Set to store the session in a separate state service.
Sql server Sets the session to be stored in SQL Server.

The optional properties are:

Property Options Describe
Cookieless Set up where the client's session information is stored
Ture Using cookieless mode
False Use cookie mode, which is the default value.
Timeout The server automatically discards session information after a few minutes of setup. Default is 20 minutes
stateConnectionString Sets the server name and port number to use when the session information is stored in the status service, for example: "tcpip=127.0.0.1:42424". When the value of mode is stateserver , this property is required.
sqlConnectionString Sets the connection string when connecting to SQL Server. For example, "Data source=localhost;integrated security=sspi;initial catalog=northwind". This property is required when the value of mode is SQL Server .
stateNetworkTimeout Sets the TCP/IP connection between the Web server and the server that stores the state information when the session state is stored in StateServer mode, after a few seconds of idle time. The default value is 10 seconds.
ASP. Storage of client session state in net

In our introduction to the session model above, you can find that the session state should be stored in two places, respectively, the client and server side. The client is only responsible for saving the SessionID of the corresponding Web site, while other session information is saved on the server side. In ASP, the client's SessionID is actually stored as a cookie. If a user chooses to disable cookies in the browser's settings, he or she will not be able to enjoy the convenience of the session, or even have access to some Web sites. In order to solve the above problem, the client's session information storage mode in asp.net is divided into two kinds: cookie and cookieless.

Asp. NET, the session information is stored by default in the client or by using cookies. If we want to store session information in a cookieless way on the client side, the following methods are available:

Locate the root directory of the current Web application, open the Web.config file, and locate the following paragraph:

<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "20"
/>

The cookieless= "false" in this passage is changed to: Cookieless= "true", so that the client's session information is no longer stored using cookies, but rather it is stored through the URL. Close the current IE, open a new IE, and visit the Web application again, and you will see something like this:

One of the http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx is the client's session ID, which is highlighted in bold. Note that this information is automatically added by IIS and does not affect previously normal connections. ASP. Storage of server-side session state in net

preparatory work

For you to experience the phenomenon better, you can create a page called Sessionstate.aspx and add the following code to the <body></body>.

<scriptrunat= "Server" >
Sub Session_add (sender as Object, E as EventArgs)
Session ("mysession") = Text1. Value
Span1. InnerHtml = "Session data updated! <p>your session contains: <font color=red> "&
Session ("MySession"). ToString () & "</font>"
End Sub

Sub checksession (sender as Object, EAs EventArgs)
If (Session ("MySession") are nothing) Then
Span1. InnerHtml = "Nothing, session DATA lost!"
Else
Span1. InnerHtml = "Your session contains: <font color=red>" &
Session ("MySession"). ToString () & "</font>"
End If
End Sub
</script>
<formrunat= "Server" id= "Form2" >
<inputid= "Text1" type= "text" runat= "server" name= "Text1" >
<inputtype= "Submit" runat= "Server" onserverclick= "Session_add"
Value= "ADD to Session State" id= "Submit1" name= "Submit1" >
<inputtype= "Submit" runat= "Server" onserverclick= "Checksession"
Value= "View Session State" id= "Submit2" name= "Submit2" >
</form>
<fontsize= "6" ><spanid= "Span1" runat= "Server"/></font>

This sessionstate.aspx page can be used to test whether session information has been lost on the current server. to store server session information in a process

Let's go back to the paragraph in the Web.config document:

<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "20"
/>

When the value of mode is InProc , it indicates that the server is using this mode.

This approach, like the pattern in previous ASP, is where the server stores session information in the IIS process. This information will be lost when IIS is shut down and reset. But this model also has its own biggest advantage, is the highest performance. All session information should be stored in the IIS process, so IIS can quickly access this information, which is much faster than storing session information outside of the process or storing the session information in SQL Server. This pattern is also the default way of ASP.net.

Okay, now let's do an experiment. Open just the Sessionstate.aspx page, enter some characters, so that it stored in the session. Then, let's get IIS back up. Note that instead of stopping the current site from starting again, click the right mouse button on the local Machine name node in IIS and select Restart IIS. (When you want to use NT4, restart IIS must restart the computer to do, Microsoft is really @#$%^&) back to the Sessionstate.aspx page, check the session information just now, found that the information has been lost. Storing server session information outside the process

First, let's open the Admin tool-> Service and find the service named: ASP.net State Service to launch it. In fact, this service is to start a process to save session information. After starting this service, you can see a process called Aspnet_state.exe from the Windows Task Manager-> process, which is the process of saving session information.

Then, return to the previous paragraph in the Web.config file and change the value of mode to stateserver. After saving the file, reopen an IE, open the sessionstate.aspx page, and save some information to the session. At this point, let us restart IIS, and then go back to the sessionstate.aspx page to see the session information just now, found not lost.

In fact, the way in which session information is stored outside the process means that it is not only possible to store information in a native process, but also to store session information in the process of other servers. Instead of changing the value of mode to stateserver, you need to configure the corresponding parameters in stateconnectionstring . For example your calculation you are 192.168.0.1, you want to store the session in the IP-192.168.0.2 computer process, you need to set this: stateconnectionstring= "tcpip= 192.168.0.2:42424 ". Of course, don't forget to load the. NET Framework on a 192.168.0.2 computer and start the ASP.net State Services service. to store server session information in SQL Server

First of all, let's do some preparatory work. Start SQL Server and SQL Server Agent service. Executes a script file called InstallSqlState.sql in SQL Server. This script file creates a database in SQL Server to store session information specifically, and a SQL Server Agent job that maintains the session information database. We can find that file in the following path:

[System drive]/winnt/microsoft.net/framework/[version]/

Then open the Query Analyzer, connect to the SQL Server server, open the file just now and execute. Wait a moment, the database and the work is established. At this point, you can open Enterprise Manager, see a new database called ASPState. But this database is just a few stored procedures, no user table. In fact, session information is stored in the ASPStateTempSessions table of the tempdb database, and another Aspstatetempapplications table stores application object information in ASP. The two tables were also created by the script just now. In addition to view the Management->sql Server Agent-> job, found also a more than a job called aspstate_job_deleteexpiredsessions, The job is actually to remove expired session information from the ASPStateTempSessions table every minute.

We then return to the Web.config file and change the value of mode to SQL Server. Note that you also have to modify the value of sqlconnectionstring , the format is: sqlconnectionstring= "Data source=localhost; Integrated SECURITY=SSPI, where data source refers to the IP address of the SQL Server server, if SQL Server and IIS are a machine, write 127.0.0.1. Integrated SECURITY=SSPI means to use Windows Integrated authentication so that access to the database will be done as asp.net, and by so doing, you can get more SQL than the userid=sa;password= password Better security for the server authentication method. Of course, if SQL Server is running on another computer, you may need to maintain the consistency of both sides of the authentication through the Active Directory domain.

Again, let's do an experiment. Adding session information to the sessionstate.aspx, it is found that session information already exists in SQL Server, even if you restart the computer, the session information just now will not be lost. Now that you've seen exactly what the session information looks like, and it's stored in SQL Server, what you can do is look at your play, haha. Summary

Through this article, you can see in the session Management and maintenance, ASP. NET than the ASP has made great progress, we can more randomly select the appropriate method. For enterprise-class applications, this is undoubtedly for the server synchronization, server stability, reliability are beneficial. I believe that with the strong support of Microsoft, a new generation of E-commerce platform will be built better.

At the same time, you will find that the entire technology includes the operating system, Web services and the integration of a variety of database technologies. I believe that perhaps windows is not stable with UNIX, IIS is not Apache stable, SQL Server is not powerful Oracle, but who can make them so perfectly linked together. So, although every aspect of Microsoft is not too strong, but if the Microsoft's things are integrated together, who dare to say he is not strong. Microsoft is Microsoft.

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.