Home  >  Article  >  Backend Development  >  Detailed explanation of using ASP.NET Session

Detailed explanation of using ASP.NET Session

高洛峰
高洛峰Original
2017-01-07 09:49:272541browse

Session model introduction

What is Session? Simply put, it is a number given by the server to the client. When a WWW server is running, there may be several users browsing the website running on this server. When each user establishes a connection to this WWW server for the first time, he establishes a Session with this 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. We will see what it actually looks like in the following experiment.

This unique SessionID has great practical significance. When a user submits a form, the browser will automatically append the user's SessionID to the HTTP header information (this is an automatic function of the browser and the user will not notice it). When the server completes processing the form, it will return the result. To the user corresponding to SessionID. Just imagine, if there is no SessionID, when two users register at the same time, how can the server know which user submitted which form? Of course, SessionID has many other functions, which we will mention later.

In addition to SessionID, each Session also contains a lot of other information. But for those who write ASP or ASP.NET programs, the most useful thing is to store their own information for each user by accessing the built-in Session object of ASP/ASP.NET. For example, if we want to know how many pages users who visit our website have browsed, we may add to each page that users may visit:

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

Through the following sentence, users can know that they have browsed A few pages:

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

Some readers may ask: Where does this Session (".."), which looks like an array, come from? Do you need me to define it? In fact, this Session object is a built-in object of the WWW server with ASP interpretation capabilities. In other words, this object has been defined for you in the ASP system, you just need to use it. The .. in Session(“..”) is like the variable name, and the $$$ in Session(“..”)=$$$ is the value of the variable. You only need to write a sentence, and the value in the variable can be accessed in every page of this user.

In fact, ASP has a total of 7 built-in objects, including Session, Application, Cookie, Response, Request, Server, etc. There are similar objects in other server-side scripting languages ​​such as JSP, PHP, etc., but the names or usage methods are different.

Defects in the ASP Session function

Currently, ASP developers are using the powerful function of Session, but during their use, they discovered that ASP Session has the following defects:

Process dependency: ASP Session status is stored in the IIS process, which is the inetinfo.exe program. So when the inetinfo.exe process crashes, this information is lost. In addition, restarting or closing the IIS service will cause information loss.

Limitations in the scope of use of Session status: When a user visits another website from one website, the Session information will not be transferred with it. For example: Sina website may have more than one WWW server. After a user logs in, he has to browse various channels, but each channel is on a different server. What if he wants to share session information on these WWW servers?

Cookie dependency: In fact, the client's Session information is stored in Cookie. If the client completely disables the Cookie function, he will not be able to enjoy the functions provided by Session.

In view of the above defects of ASP Session, Microsoft designers made corresponding improvements when designing and developing ASP.NET Session, completely overcoming the above defects, making ASP.NET Session a more powerful function .

Introduction to Web.config file

Some ASP.NET programmers say: Web.config file? I have never heard of it, but doesn’t the program I wrote also run normally? Yes, you are right, the program can run normally without the Web.config file. However, if you build a large website and need to make some overall configuration of the entire website, such as which language the entire website pages are written in, the website's security authentication mode, session information storage method, etc., then you need to use Web.config file. Although some options in the Web.config file can be configured through IIS, if there are corresponding settings in Web.config, they will overwrite the configuration in IIS. Moreover, the greatest convenience of the Web.config file is that you can access the settings in Web.config in the ASP.NET page by calling the System.web namespace.

There are two types of Web.config, namely server configuration file and Web application configuration file. They are both named Web.config. This configuration file will save a series of information including which language the web page in the current IIS server is written in, the application security authentication mode, and the session information storage method. This information is saved using XML syntax. If you want to edit it, just use a text editor.

其中服务器配置文件会对IIS服务器下所有的站点中的所有应用程序起作用。在.NET Framework 1.0中,服务器的Web.config文件是存在:\WinNT\Microsoft.NET\Framework\v1.0.3705中的。

而Web应用程序配置文件Web.config则保存在各个Web应用程序中。例如:当前网站的根目录\Inetpub\wwwroot,而当前的Web应用程序为MyApplication,则Web应用程序根目录就应为:\Inetpub\wwwroot\MyApplication。如果你的网站有且只有一个Web应用程序,一般说来应用程序的根目录就是\Inetpub\wwwroot。如果想添加一个Web应用程序,在IIS中添加一个具有应用程序起始点的虚拟目录就行了。这个目录下的文件及目录将被视为一个Web应用程序。但是,这样通过IIS添加Web应用程序是不会为你生成Web.config文件的。如果想创建一个带有Web.config文件的Web应用程序,需要使用Visual Studio.NET,新建一个Web应用程序项目。

Web应用程序的配置文件Web.config是可选的,可有可无。如果没有,每个Web应用程序会使用服务器的Web.config配置文件。如果有,则会覆盖服务器Web.config配置文件中相应的值。

在ASP.NET中,Web.config修改保存后会自动立刻成效,不用再像ASP中的配置文件修改后需要重新启动Web应用程序才能生效了。

Web.config文件中的Session配置信息

打开某个应用程序的配置文件Web.config后,我们会发现以下这段:

这一段就是配置应用程序是如何存储Session信息的了。我们以下的各种操作主要是针对这一段配置展开。让我们先看看这一段配置中所包含的内容的意思。sessionState节点的语法是这样的:

必须有的属性是

ASP.NET Session使用详解

可选的属性是:

ASP.NET Session使用详解

ASP.NET中客户端Session状态的存储

在我们上面的Session模型简介中,大家可以发现Session状态应该存储在两个地方,分别是客户端和服务器端。客户端只负责保存相应网站的SessionID,而其他的Session信息则保存在服务器端。在ASP中,客户端的SessionID实际是以Cookie的形式存储的。如果用户在浏览器的设置中选择了禁用Cookie,那末他也就无法享受Session的便利之处了,甚至造成不能访问某些网站。为了解决以上问题,在ASP.NET中客户端的Session信息存储方式分为:Cookie和Cookieless两种。

ASP.NET中,默认状态下,在客户端还是使用Cookie存储Session信息的。如果我们想在客户端使用Cookieless的方式存储Session信息的方法如下:

找到当前Web应用程序的根目录,打开Web.Config文件,找到如下段落:

这段话中的cookieless="false"改为:cookieless="true",这样,客户端的Session信息就不再使用Cookie存储了,而是将其通过URL存储。关闭当前的IE,打开一个新IE,重新访问刚才的Web应用程序,就会看到类似下面的样子:

其中,http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx中黑体标出的就是客户端的Session ID。注意,这段信息是由IIS自动加上的,不会影响以前正常的连接。

ASP.NET中服务器端Session状态的存储

准备工作

为了您能更好的体验到实验现象,您可以建立一个叫做SessionState.aspx的页面,然后把以下这些代码添加到6c04bd5ca3fcae76e30b72ad730ca86d36cc49f0c466276486e50c850b7e4956中。


Sub Session_Add(sender As Object, e As EventArgs)
   Session("MySession") = text1.Value
   span1.InnerHtml = "Session data updated! 

Your session contains: " & \            Session("MySession").ToString() & "" 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: " & \              Session("MySession").ToString() & "" End If End Sub      

这个SessionState.aspx的页面可以用来测试在当前的服务器上是否丢失了Session信息。

将服务器Session信息存储在进程中

让我们来回到Web.config文件的刚才那段段落中:

当mode的值是InProc时,说明服务器正在使用这种模式。

这种方式和以前ASP中的模式一样,就是服务器将Session信息存储在IIS进程中。当IIS关闭、重起后,这些信息都会丢失。但是这种模式也有自己最大好处,就是性能最高。应为所有的Session信息都存储在了IIS的进程中,所以IIS能够很快的访问到这些信息,这种模式的性能比进程外存储Session信息或是在SQL Server中存储Session信息都要快上很多。这种模式也是ASP.NET的默认方式。

好了,现在让我们做个试验。打开刚才的SessionState.aspx页面,随便输入一些字符,使其存储在Session中。然后,让我们让IIS重起。注意,并不是使当前的站点停止再开始,而是在IIS中本机的机器名的节点上点击鼠标右键,选择重新启动IIS。(想当初使用NT4时,重新启动IIS必须要重新启动计算机才行,微软真是@#$%^&)返回到SessionState.aspx页面中,检查刚才的Session信息,发现信息已经丢失了。

将服务器Session信息存储在进程外

首先,让我们来打开管理工具->服务,找到名为:ASP.NET State Service的服务,启动它。实际上,这个服务就是启动一个要保存Session信息的进程。启动这个服务后,你可以从Windows任务管理器->进程中看到一个名为aspnet_state.exe的进程,这个就是我们保存Session信息的进程。

然后,回到Web.config文件中上述的段落中,将mode的值改为StateServer。保存文件后的重新打开一个IE,打开SessionState.aspx页面,保存一些信息到Session中。这时,让我们重起IIS,再回到SessionState.aspx页面中查看刚才的Session信息,发现没有丢失。

实际上,这种将Session信息存储在进程外的方式不光指可以将信息存储在本机的进程外,还可以将Session信息存储在其他的服务器的进程中。这时,不光需要将mode的值改为StateServer,还需要在stateConnectionString中配置相应的参数。例如你的计算你是192.168.0.1,你想把Session存储在IP为192.168.0.2的计算机的进程中,就需要设置成这样:stateConnectionString="tcpip=192.168.0.2:42424"。当然,不要忘记在192.168.0.2的计算机中装上.NET Framework,并且启动ASP.NET State Services服务。

将服务器Session信息存储在SQL Server中

首先,还是让我们来做一些准备工作。启动SQL Server和SQL Server代理服务。在SQL Server中执行一个叫做InstallSqlState.sql的脚本文件。这个脚本文件将在SQL Server中创建一个用来专门存储Session信息的数据库,及一个维护Session信息数据库的SQL Server代理作业。我们可以在以下路径中找到那个文件:

[system drive]\winnt\Microsoft.NET\Framework\[version]\

然后打开查询分析器,连接到SQL Server服务器,打开刚才的那个文件并且执行。稍等片刻,数据库及作业就建立好了。这时,你可以打开企业管理器,看到新增了一个叫ASPState的数据库。但是这个数据库中只是些存储过程,没有用户表。实际上Session信息是存储在了tempdb数据库的ASPStateTempSessions表中的,另外一个ASPStateTempApplications表存储了ASP中Application对象信息。这两个表也是刚才的那个脚本建立的。另外查看管理->SQL Server代理->作业,发现也多了一个叫做ASPState_Job_DeleteExpiredSessions的作业,这个作业实际上就是每分钟去ASPStateTempSessions表中删除过期的Session信息的。

接着,我们返回到Web.config文件,修改mode的值改为SQLServer。注意,还要同时修改sqlConnectionString的值,格式为:sqlConnectionString="data source=localhost; Integrated Security=SSPI;",其中data source是指SQL Server服务器的IP地址,如果SQL Server与IIS是一台机子,写127.0.0.1就行了。Integrated Security=SSPI的意思是使用Windows集成身份验证,这样,访问数据库将以ASP.NET的身份进行,通过如此配置,能够获得比使用userid=sa;password=口令的SQL Server验证方式更好的安全性。当然,如果SQL Server运行于另一台计算机上,你可能会需要通过Active Directory域的方式来维护两边验证的一致性。


更多ASP.NET Session使用详解相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn