有时候你希望你的页面“一直活着”。也就是说,如果一个用户填写一个复杂的表单,在用户完成之前。你一定不希望session过期。否者用户可能因此变得非常恼怒。 1 <system.web>
2 <sessionState timeout="2"> 3 </sessionState> 4 </system.web> 为了追踪具体发生了什么,使用一个公用的函数ODS(在MiscUtilities类中) 1 // ---- ODS (Output Debug String) ----------------------
2 public static void ODS(string Msg) 3 { 4 String Out = String.Format("{0} {1}", DateTime.Now.ToString("hh:mm:ss.ff"), Msg); 5 System.Diagnostics.Debug.WriteLine(Out); 6 } 7 为了观察session的状态事件,我在global.asax中添加用于调试的字符串。 1 <%@ Application Language="C#" %>
2 <script RunAt="server"> 3 4 void Application_Start(object sender, EventArgs e) 5 { 6 MiscUtilities.ODS("****ApplicationStart"); 7 } 8 void Session_Start(object sender, EventArgs e) 9 { 10 MiscUtilities.ODS("Session_Start"); 11 } 12 void Session_End(object sender, EventArgs e) 13 { 14 MiscUtilities.ODS("Session_End"); 15 } 16 下面是详细步骤:由于我们需要在服务端有一个方法供客户端调用。故使用一个WebMethod方法。 1 <asp:ScriptManager ID="ScriptManager1" runat="server"
2 EnablePageMethods="true"> 3 </asp:ScriptManager>
1 public partial class _Default : System.Web.UI.Page
2 { 3 [WebMethod(EnableSession=true ) ] 4 public static void PokePage() 5 { 6 // called by client to refresh session 7 MiscUtilities.ODS("Server: I am poked"); 8 } 9 我们需要有一个客户端的JavaScript定时地去调用服务端的方法。 1 <script type="text/javascript">
2 var HeartBeatTimer; 3 function StartHeartBeat() 4 { 5 // pulse every 10 seconds 6 if (HeartBeatTimer == null) 7 HeartBeatTimer = setInterval("HeartBeat()", 1000 * 10); 8 } 9 function HeartBeat() 10 { 11 // note: ScriptManger must have: EnablePageMethods="true" 12 Sys.Debug.trace("Client: Poke Server"); 13 PageMethods.PokePage(); 14 } 15 <body id="MyBody" onload="StartHeartBeat();"> 16 没有"心跳"的,输入如下: 1 10:22:43.03 ****ApplicationStart
2 10:22:45.13 Session_Start 3 10:25:00.00 Session_End 有"心跳"的,输出如下: 1 10:26:06.10 ****ApplicationStart
2 10:26:08.05 Session_Start 3 Client: Poke Server 4 10:26:18.93 Server: I am poked 5 Client: Poke Server 6 10:26:28.95 Server: I am poked 7 Client: Poke Server 8 10:26:38.96 Server: I am poked 9 Client: Poke Server 10 10:26:48.98 Server: I am poked 11 12 . . . (lines deleted) 13 14 Client: Poke Server 15 10:29:59.45 Server: I am poked 16 Client: Poke Server 17 10:30:09.47 Server: I am poked 18 Client: Poke Server 19 10:30:19.48 Server: I am poked 20 21 . . . (lines deleted) 22 这样看起来客户端闲置的时候,session仍然活着,也就是网站“心跳”着。 (有点扯淡) (责任编辑:admin) |