检测ASP.NET MVC上的会话到期

我建立了一个购物车,使用会话状态来保存购物车数据,同时用户正在浏览商店。

我有一个问题,如果我在购物车的step1上长时间打开浏览器窗口,然后按“转到第2步”,我的操作会抛出错误,因为step2操作假定会话未过期且ShopCart对象处于正确状态。

我希望这个场景对我的用户更好,但我想我需要以某种方式检测会话是否已过期,以便在下一个请求时我可以将它们抛给Step1。

我发现以下代码声称要解决问题,但它对我不起作用。

IsNewSession条件为真,但条件

if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) { // handle expired session } 

始终返回false,它永远不会处理无效会话。 我糊涂了。

这在ASP.NET(和MVC)中是否可行?

方式1

将此代码放在第2页的Init / Load事件中……

  if (Context.Session != null) { if (Context.Session.IsNewSession) { string sCookieHeader = Request.Headers["Cookie"]; if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) { if (Request.IsAuthenticated) { FormsAuthentication.SignOut(); } Response.Redirect("Error Page"); } } } 

方式2

另外,您可以检查Session对象是否存在,然后再继续在第2页中使用它,如下所示:

 if (Session["Key"] != null) { Object O1 = (Object) Session["Key"]; } else { Response.Redirect("ErrorPage.aspx"); } 

国王的回答对我不起作用。 我在OnActionExcuting()添加了FormsAuthentication.SignOut() OnActionExcuting()Response.Redirect不起作用!

 if (Request.IsAuthenticated) { FormsAuthentication.SignOut(); } 

这是我完整的方法

 public class SessionExpireFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; // check if session is supported if (ctx.Session != null) { // check if a new session id was generated if (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)) { string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery; string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess); string loginUrl = FormsAuthentication.LoginUrl + redirectUrl; if (ctx.Request.IsAuthenticated) { FormsAuthentication.SignOut(); } RedirectResult rr = new RedirectResult(loginUrl); filterContext.Result = rr; //ctx.Response.Redirect("~/Home/Logon"); } } } base.OnActionExecuting(filterContext); } }