ASP. NET session Usage

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





What is the session? In simple terms, the server gives the client a number. When a WWW server is running, there may be a number of users browsing the Web site that is being shipped on this server. When each user establishes a connection to this WWW server for the first time, he establishes a session with the server, and the server automatically assigns it 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 experiment below.



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 information (this is the browser's automatic function, which the user will not perceive), and when the server finishes processing the form, the result is returned to the user of SessionID. 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 many other functions that we will mention later.



In addition to SessionID, a lot of other information is included in each session. However, for programs that write ASP or ASP. NET, the most useful thing is to access the asp/asp. NET has built-in session objects that store individual information for each user. For example, we would like to know about the users who visit our website and browse several pages, and we may add them to 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 the user know that they have browsed several pages:


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


Some readers may ask, "This is a session (".. ") that looks like an array. Where did it come from? Do I need to define it? In fact, this session object is the built-in object of the WWW server with ASP interpretation capability. In other words, the ASP system has already defined the object for you, you just need to use it. where session ("..") In the.. Just like the variable name, Session ("..") The $$$ in =$$$ is the value of the variable. All you have to do is write a word that you can access on each page of the user. The value in the variable.



In fact, the ASP built a total of 7 objects, there is session, application, cookies, Response, Request, server and so on. In other server-side scripting languages such as JSP, PHP and so on, there are similar objects, just called or the use of the method is not the same.



The defect of the function of ASP session



Currently, ASP developers are using the session as a powerful feature, but in their use of the process found that the ASP session has the following defects:



Process dependencies: The ASP session state is stored in the IIS process, that is, the Inetinfo.exe program. So when the Inetinfo.exe process crashes, the information is lost. In addition, restarting or shutting down the IIS service can result in the loss of information.



Limitations of the session state usage scope: When a user accesses a website from one site to another, the session information is not migrated in the past. For example: Sina Web site may have more than one WWW server, a user login to the various channels to browse, but each channel is on a different server, if you want to share session information in these WWW server how to do?



Cookie dependency: In fact, the client's session information is stored and cookie, 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 shortcomings of ASP session, Microsoft Designers in the design and development of the ASP. NET session was improved, completely overcome the above shortcomings, making the ASP. NET session becomes a more powerful function.



Introduction to the Web. config file



Some ASP. NET programmers say: Web. config file? I have never heard of Ah, but I write the program can not also be very normal operation? Yes, you're right, there's no Web. config file program that works. However, if you do a large web site, you need to do some overall configuration of the whole site, such as the whole site of the page in which language written, the site's security authentication mode, session information storage, 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 there is a corresponding setting in Web. config. Moreover, the greatest convenience of the Web. config file is that the settings in Web. config can be accessed in an ASP. NET page by calling the System.Web namespace.



There are two types of Web. config, the server configuration file and the website application configuration file, both of which are named Web. config. In this configuration file, you will save a series of information that is written in the language of the current IIS server, the application Security authentication mode, and the session information storage method. This information is saved using XML syntax, and if you want to edit it, you can 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 Web. config file for the server is present: \winnt\microsoft.net\framework\v1.0.3705.



Web application configuration file. config files are saved in each Web application. For example: The root directory of the current Web site \inetpub\wwwroot, and the current Web application is MyApplication, the Web application root should be: \inetpub\wwwroot\myapplication. If your site has and has only one Web application, the root directory of the application is generally \inetpub\wwwroot. If you want to add a Web application, add a virtual directory with the application start point in IIS. Files and directories in this directory will be treated as a Web application. However, the Web application is not generated for you by using IIS. If you want to create a Web application with a. config file, you will need to use Visual Studio.NET, creating a new Web Application project.



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



In ASP. NET, the Web. config modification is saved automatically immediately, and no longer needs to be restarted as soon as the configuration file in ASP is modified to take effect.



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 the deployment. Let's take a look at the meaning of the content contained in this section of the configuration. The syntax for the sessionstate node is this:


<sessionState mode="Off|InProc|StateServer|SQLServer"
       cookieless="true|false"
       timeout="number of minutes"
       stateConnectionString="tcpip=server:port"
       sqlConnectionString="sql connection string"
       stateNetworkTimeout="number of seconds"
/>


Required properties are






The optional properties are:






Asp. The storage of client session state in net



In the introduction of the session model above, we can find that the session state should be stored in two places, namely the client and server side. The client is only responsible for saving the SessionID of the corresponding website, while the other session information is saved on the server side. In ASP, the SessionID of the client is actually stored in the form of 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 certain websites. In order to solve the above problems, the client's session information is stored in asp: Two kinds of cookies and cookieless.



Asp. NET, by default, the session information is stored on the client or using a cookie. If we want to store session information as a client using cookieless, here's how:



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 paragraph is replaced by the following: Cookieless= "true", so that the client session information is no longer stored using a cookie, but rather it is stored through a URL. Close the current IE, open a new IE, revisit the Web application, and you will see something like this:



In http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx, the client's session ID is marked in bold. Note that this information is automatically added by IIS and does not affect the previous normal connection.



Asp. The storage of server-side session state in net



Preparatory work



For you to experience the experiment better, you can create a page called sessionstate.aspx, and then add the following code to <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")Is 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>
<hrsize="1">
<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.

Store server session information in the process

Let's go back to the previous paragraph of the Web.config file:

<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, the server is using this mode.

This method is the same as the previous model in ASP, that is, the server stores Session information in the IIS process. This information will be lost when IIS is shut down and restarted. But this mode also has its biggest benefit, which is the highest performance. All session information should be stored in the IIS process, so IIS can quickly access this information. The performance of this mode is faster than storing session information out of the process or storing session information in SQL Server. a lot of. This mode is also the default way of ASP.NET.

Okay, now let's experiment. Open the SessionState.aspx page just now, and enter some characters to store it in the Session. Then, let's restart IIS. Note that instead of stopping and restarting the current site, right-click the node of the local machine name in IIS and select Restart IIS. (If you want to use NT4, you must restart the computer to restart IIS. Microsoft really @ # $% ^ &) Return to the SessionState.aspx page, check the session information just now, and find that the information has been lost.

Store server session information out of process

First, let's open Administrative Tools-> Services, find the service named: ASP.NET State Service, and start it. In fact, this service is to start a process to save Session information. After starting this service, you can see a process named aspnet_state.exe from the Windows Task Manager-> Process. This is our process to save Session information.

Then, go back to the above paragraph in the Web.config file and change the value of mode to StateServer. After saving the file, re-open an IE, open the SessionState.aspx page, and save some information to the Session. At this point, let's restart IIS, and then return to the SessionState.aspx page to view the previous Session information, and found that nothing was lost.

In fact, this way of storing Session information outside the process not only means that the information can be stored outside the local process, but also the Session information can be stored in the processes of other servers. At this time, not only need to change the value of mode to StateServer, but also configure corresponding parameters in stateConnectionString. For example, if you calculate that you are 192.168.0.1, and you want to store the Session in the process of the computer with IP 192.168.0.2, you need to set it like this: stateConnectionString = "tcpip = 192.168.0.2: 42424". Of course, don't forget to install the .NET Framework on the computer at 192.168.0.2 and start the ASP.NET State Services service.

Store server session information in SQL Server

First, let's do some preparations. Start the SQL Server and SQL Server Agent services. Execute a script file called InstallSqlState.sql in SQL Server. This script file will create a database in SQL Server specifically to store Session information, and a SQL Server Agent job to maintain 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 before and execute. After a while, the database and job are set up. At this point, you can open the Enterprise Manager and see that a new database called ASPState has been added. But this database is just some stored procedures, there is no user table. In fact, Session information is stored in the ASPStateTempSessions table of the tempdb database, and another ASPStateTempApplications table stores the Application object information in ASP. These two tables are also created by the script just now. In addition, check Management-> SQL Server Agent-> Jobs, and found that there is also a job called ASPState_Job_DeleteExpiredSessions. This job is actually going to delete the expired Session information in the ASPStateTempSessions table every minute.

Next, we return to the Web.config file and change the value of mode to SQLServer. Note that you also need to modify the value of sqlConnectionString at the same time, the format is: sqlConnectionString = "data source = localhost; Integrated Security = SSPI;", where data source refers to the IP address of the SQL Server server. Just write 127.0.0.1. Integrated Security = SSPI means using Windows Integrated Authentication. In this way, accessing the database will be performed as ASP.NET. With this configuration, you can obtain better security than SQL Server authentication using userid = sa; password = password. Sex. Of course, if SQL Server is running on another computer, you may need to maintain the consistency of authentication on both sides through the Active Directory domain.






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.