【问题标题】:Session is not timing out in ASP.NET web applicationASP.NET Web 应用程序中的会话未超时
【发布时间】:2011-09-23 20:28:46
【问题描述】:

我正在开发一个 ASP.NET 3.5 WebForms 应用程序,我希望会话在一段时间后超时。之后,如果用户尝试做任何事情,应用程序应该将他们重定向到一个页面,说明会话已超时并且他们需要重新开始。据我所知,相当标准的东西。

但是,我似乎无法让会话超时来测试此功能,无论是从 Visual Studio 还是从 IIS 运行。这是我在 web.config 中的会话状态设置:

<sessionState mode="SQLServer"
              allowCustomSqlDatabase="true"
              sqlConnectionString="<ConnectionString>"
              cookieless="false"
              timeout="1" />

这是我测试会话超时的方法:

public bool IsSessionTimeout
{
    get
    {
        // If the session says its a new session, but a cookie exists, then the session has timed out.
        if (Context.Session != null && Session.IsNewSession)
        {
            string cookie = Request.Headers["Cookie"];
            return !string.IsNullOrEmpty(cookie) && cookie.IndexOf("ASP.NET_SessionId") >= 0;
        }
        else
        {
            return false;
        }
    }
}

似乎Session.IsNewSession 总是返回false,这是有道理的,因为在我的 Global.asax.cs 中永远不会调用 Session_End 方法。我错过了什么?

【问题讨论】:

  • 我相信 Session_End 只在进程会话中被调用。检查会话 ID 以查看是否在时间到期后生成了新 ID。

标签: c# asp.net iis session-timeout


【解决方案1】:

我这样做:

        if (Session["myUser"] != null)
            myUser = (User)Session["myUser"];
        else
            myUser = null;

        //User must be logged in, if not redirect to the login page - unless we are already running the login page.
        if ((myUser == null) && (Request.Url.AbsolutePath != "/Login.aspx"))
            Response.Redirect("Login.aspx?Mode=Timeout", true);

在我的一个网站的母版页的 page_init 中。你可以很容易地适应你想要的东西。基本上,检查会话中应该存在的内容,如果不存在,则您的会话已超时,您可以采取适当的措施。

在我的例子中,它们被重定向到登录页面。在您的情况下,每当他们开始您的“流程”时,您就设置了一个会话变量。在每个页面请求中,查看该项目是否仍然存在于会话中。

【讨论】:

  • 当我看到你的回答时,我认为它会解决我的问题,但由于某种原因,我的会话对象在超时时间过去后仍然存在。我认为 SQL Server 可能没有正确设置,但不幸的是,我对此没有太多控制权。我最终实施的将您的答案与经过时间的手动检查相结合。
【解决方案2】:

这是我最终实施的。

在 Global.asax.cs 中:

protected void Session_Start(object sender, EventArgs e)
{
    Session[SessionKeys.SessionStart] = DateTime.Now;
}

在我的页面的基类中:

public bool IsSessionTimeout
{
    get
    {
        DateTime? sessionStart = Session[SessionKeys.SessionStart] as DateTime?;
        bool isTimeout = false;

        if (!sessionStart.HasValue)
        {
            // If sessionStart doesn't have a value, the session has been cleared, 
            // so assume a timeout has occurred.            
            isTimeout = true;
        }
        else
        {
            // Otherwise, check the elapsed time.
            TimeSpan elapsed = DateTime.Now - sessionStart.Value;
            isTimeout = elapsed.TotalMinutes > Session.Timeout;
        }

        Session[SessionKeys.SessionStart] = DateTime.Now;
        return isTimeout;
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2018-01-30
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多