2011-03-25 60 views
8

我目前正在爲我的ASP.NET 3.5 MVC 2項目開發一個會話過期的邏輯塊,以註銷用戶並將其重定向到AccountController LogOn操作。谷歌瀏覽器的ASP.NET MVC Session.IsNewSession問題

我對所有關心會話狀態的操作都有以下屬性,這段代碼適用於IE 8,但不適用於Firefox 4或Google Chrome 10.症狀是當我嘗試導航到代表的視圖時通過使用[SessionExpireFilter]屬性的動作,即使我在30分鐘的會話中只有幾秒鐘,下面代碼中的ctx.Session.IsNewSession屬性每次都會評估爲「true」。

public class SessionExpireFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     HttpContext ctx = HttpContext.Current; 

     // check if session is supported 
     if (ctx.Session != null && ctx.Session.IsNewSession) 
     { 
      // If it says it is a new session, but an existing cookie exists, then it must 
      // have timed out 
      string sessionCookie = ctx.Request.Headers["Cookie"]; 
      if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) 
      { 
       FormsAuthentication.SignOut(); 
       ctx.Response.Redirect("~/Account/LogOn"); 
      } 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 

有什麼方法可以找出爲什麼Chrome和Firefox的行爲是這樣的,但IE瀏覽器不是?提前致謝。

編輯:這是不工作在FF,因爲我原本相信。我登錄後立即將其定向到LogOn操作,並嘗試使用我的SessionExpireFilter屬性訪問操作。

回答

14

ASP.NET將爲每個請求創建一個新會話,除非您在其中存儲了某些內容。 嘗試將下面的代碼添加到您的Global.asax。它適用於我的MVC2和MVC3應用程序,具有相同的SessionExpireFilterAttribute

protected void Session_Start() 
{ 
    Session["Dummy"] = 1; 
} 
+1

引人入勝。所以IE不要求新會話的事實是這裏實際的不尋常行爲? – PancakeParfait 2011-03-25 16:47:18

+1

這就像一個魅力,謝謝你的洞察力! – PancakeParfait 2011-03-25 16:52:53

+0

這與瀏覽器無關,它是ASP.NET的行爲。 – 2012-05-03 09:36:42

1

我們可以在MVC appliaction Golbal.asax文件添加在session_start方法。

protected void Session_Start(object sender, EventArgs e) 
     {      
     HttpContext.Current.Session.Add("UserId" , null); 
     } 

然後,當應用開始您的會話將被創建。然後會議將不會isNewSession「真」,否則將永遠「真」