2013-05-03 37 views
0

我試圖檢測Asp.NET會話超時重定向用戶到超時頁面;我檢查了各種方法,他們大多類似檢測ASP.NET會話超時 - ASP.NET_SessionId方法不工作

http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.2

(如果Session.IsNewSessionASP.NET_SessionId cookie存在,則是一個超時)

的問題是,「ASP.NET_SessionId」 cookie是永遠對我來說,即使我剛剛開始調試,因此第一次啓動網站時總會出現虛假超時標誌。

UPDATE: 爲了進行測試,我剛剛創建了以下代碼一個空的Asp.NET Web應用程序:

BasePage.cs

using System; 
using System.Web.UI; 

namespace TestApp.classes 
{ 
    public class BasePage : Page 
    { 
     protected override void OnInit(EventArgs e) 
     { 
      base.OnInit(e); 

      if (Context.Session != null) 
      { 
       if (Session.IsNewSession) 
       { 
        string szCookieHeader = Request.Headers["Cookie"]; 
        if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) 
        { 
         Response.Redirect("sessionTimeout.htm"); 
        } 
       } 
      } 
     } 
    } 
} 

的Global.asax

using System; 

namespace TestApp 
{ 
    public class Global : System.Web.HttpApplication 
    { 

     protected void Application_Start(object sender, EventArgs e) 
     { 

     } 

     protected void Session_Start(object sender, EventArgs e) 
     { 
      var a = ""; 
     } 

     protected void Application_BeginRequest(object sender, EventArgs e) 
     { 

     } 

     protected void Application_AuthenticateRequest(object sender, EventArgs e) 
     { 

     } 

     protected void Application_Error(object sender, EventArgs e) 
     { 

     } 

     protected void Session_End(object sender, EventArgs e) 
     { 
      var b = ""; 
     } 

     protected void Application_End(object sender, EventArgs e) 
     { 

     } 
    } 
} 

WebForm1.aspx

using System; 
using TestApp.classes; 

namespace TestApp 
{ 
    public partial class WebForm1 : BasePage 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 

的Web.config

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
     <compilation debug="true" targetFramework="4.5" /> 
     <httpRuntime targetFramework="4.5" /> 
     <sessionState timeout="1"></sessionState> 
    </system.web> 

</configuration> 

然後打F5,以及i將被重定向到sessionTimeout.htm。爲什麼?

+0

如果cookie是始終存在的,你爲什麼要檢查?必須僅檢查'Session.IsNewSession'或刪除Cookie – 2013-05-03 09:50:41

+0

,因爲理論上ASP.NET_SessionId cookie在第一次訪問時不會出現。 – 2013-05-03 09:53:44

+0

您必須使用Cookie.Discard屬性,並且您可以在web.config中更改cookie狀態false。 – 2013-05-03 09:56:55

回答

0

您在開發網站時不必使用cookie。還有其他存儲數據的方式,例如你可以存儲在數據庫中的特定用戶的數據

注意,在web.config"Cookieless = false" attrubute SessionState元素,這意味着當前會話的會話ID將被保存在客戶端機器作爲cookie

<sessionState cookieless="true" /> 

默認ASP.NET會話狀態的設置在machine.config文件中定義,並可在應用程序的根文件夾中的web.config文件中覆蓋。通過確保上述行出現在根web.config文件中,將啓用Cookie會話

參考http://msdn.microsoft.com/en-us/library/aa479314.aspx

所以只檢查Session.IsNewSession和禁用cookie的

+0

在我看到的所有方法中,沒有人建議使用無Cookie模式(並且我需要cookies);也許在我的配置上有其他錯誤? – 2013-05-03 10:45:33

+0

你能分享你的代碼部分嗎? – 2013-05-03 10:46:51