浏览器关闭时会话超时

本文关键字:会话 超时 浏览器 | 更新日期: 2023-09-27 18:03:28

我使用以下代码来检测会话过期:

public class SessionActionFilterAttribute : ActionFilterAttribute
{
    /// <summary>Called by the ASP.NET MVC framework before the action method executes.</summary>
    /// <param name="filterContext">The filter context.</param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // The following code is used for checking if a session has timed out. The default timeout value for ASP.NET is 20mins.
        // The timeout value can be overriden in the Web.config file using the sessionState tag's timeout attribute.
        // <sessionState timeout="5"></sessionState>
        // Check for an existing session.
        if (null != filterContext.HttpContext.Session)
        {
            // Check if we have a new session.
            // IsNewSession cannot discern between: is it a new visitor with fresh session, or an existing visitor with expired session.
            if (filterContext.HttpContext.Session.IsNewSession)
            {
                string cookieHeaders = filterContext.HttpContext.Request.Headers["Cookie"];
                // Check if session has timed out.
                // Does session cookie exist, if so ASP.NET session is expired
                if ((null != cookieHeaders) && (cookieHeaders.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    if (filterContext.HttpContext.Request.IsAuthenticated)
                    {
                        FormsAuthentication.SignOut();
                    }
                    // Redirect to login.
                    filterContext.Result = new RedirectToRouteResult(
                                                                    new RouteValueDictionary 
                                                                    { 
                                                                        { "controller", "Account" }, 
                                                                        { "action", "Index" },
                                                                        { "timeout", "True"}
                                                                    });
                    return;
                }
            }
        }
        // Else continue with action as usual.
        // Session is not expired and function will return false, could be new session, or existing active session
        base.OnActionExecuting(filterContext);
    }
}

它在一定程度上工作得很好…

当用户在会话超时前登录并关闭浏览器时(没有注销)…

然后尝试再次查看网站并在会话超时后重新登录,它不断重定向到登录页面,即上面的代码认为会话已经连续过期,但我猜由于某种原因cookie仍然是"过期"。

我在这里错过了什么吗?

注:我在web.config

中使用以下内容
<sessionState timeout="1"></sessionState>

浏览器关闭时会话超时

哎呀....我在重定向之前添加了以下内容,似乎已经解决了....问题只是多做一点测试来确保:

if (filterContext.HttpContext.Request.Cookies["ASP.NET_SessionId"] != null)
{
    filterContext.HttpContext.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-1);
}
filterContext.HttpContext.Session.Abandon();