三种Session:
1.InProc(进程内)-Asp.Net默认就是这种
优点:速度快
缺点:但内存小,存储有限,易爆满导致重启数据丢失
进程外:可以在IIS或ASPNET服务意外关闭时继续保持状态,注意此时存储到session中的对象必须支持序列化:
2.StateServer:使用aspnet_state.exe
2.1开启服务:我的电脑-管理-服务与应用程序-服务-ASP.NET State Service(ASP.NET 状态服务)
2.2修改配置文件:
<system.web>节点中添加<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424"/>【ASP.NET 状态服务端口号默认:42424】
2.3ASP.NET 状态服务只限本机使用如果需要保存外部的Session需要修改注册表
设置是否允许远程使用,位置:C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRenoteConnection 值改为 1
测试代码如下:
using System; namespace WebForm { public partial class OutSession : System.Web.UI. Page { protected void Page_Load( object sender, EventArgs e) { if (Session["key" ] != null) { Person p = (Person )Session[ "key"]; Response.Write(p.GetName()); } else { Session[ "key" ] = new Person( "piziyimao" ); } } } [ Serializable] //必须是可序列化的类 public class Person { public Person(string n) { name = n; } private string name; public string GetName() { return name; } } }
Web.Config
<? xml version =" 1.0 "?> < configuration> < system.web > < compilation debug = "true " targetFramework = "4.0 " /> < sessionState mode = "StateServer " stateConnectionString =" tcpip=localhost:42424 "/> </ system.web > < connectionStrings > < add name = "ConnStr " connectionString =" server=.;database=School;uid=sa;pwd=123456 " /> </ connectionStrings > </ configuration>
3.SQLServer
3.1使用aspnet_regsql.exe运行Session数据库脚本脚本路径C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
临时储存区:InstallSqlState.sql & UninstallSqlState.sql
永久储存区:InstallPersistSqlState.sql & UninstallPersistSqlState.sql(InstallPersistSqlState需要使用ASPState数据库 需自己创建)
3.2修改配置文件如下:
<? xml version =" 1.0 "?> < configuration> < system.web > < compilation debug = "true " targetFramework = "4.0 " /> < sessionState mode = "SQLServer"/> </ system.web > < connectionStrings > < add name = "ConnStr " connectionString =" server=.;database=School;uid=sa;pwd=123456 " /> </ connectionStrings > </ configuration>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>