如何防止AJAX轮询使Asp.Net会话保持活动状态

时间:2014-10-21 14:17:59

标签: ajax asp.net-mvc session cookies

我们有一个ASP.Net应用程序,该会话(和cookie)已经过了20分钟的滑动到期时间。 但是,我们有一些AJAX正在轮询服务器以获取新信息。当然,这样做的缺点是会话将无限期地继续,因为轮询会使得刷新到期时间保持活跃状态​​。有没有办法阻止这种情况 - 即只允许在非ajax调用中刷新会话?

关闭滑动到期并不是一个真正的选择,因为这是一个应用程序,商业用户将在电话呼叫之间的大部分时间使用它。

关于此讨论的其他Stackoverflow讨论关于维护2个单独的应用程序(一个用于经过身份验证的调用,一个用于未经身份验证的调用。我不确定这是一个选项,因为所有调用都需要进行身份验证。

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

As this question is old I am assuming it has been resolved or a workaround implemented. However, I wanted to mention that instead of AJAX polling the server to perform an operation we have utilized SignalR which allows both the client to communicate with the server via JQuery and/or the server to notify the client.

Check it out: Learn About ASP.NET SignalR

答案 1 :(得分:0)

将下面的代码添加到您要轮询的控制器操作中,并将其转换为属性以便可以在任何地方使用。该行不会延长会话超时

    [HttpPost]
    public ActionResult Run()
    {
        Response.Cookies.Remove(FormsAuthentication.FormsCookieName);

        return Json("");
    }

答案 2 :(得分:-1)

我通过在i-Frame中创建隐藏页面来完成此操作。然后使用JavaScript,它每18分钟发回一次以保持会话活跃。这非常有效。

此示例来自ASP.NET Forms项目,但可以针对MVC进行调整。

  1. 创建名为KeepSessionAlive页面的页面并添加元刷新标记

    meta id =" MetaRefresh" HTTP的当量="刷新"含量=" 21600; URL = KeepSessionAlive.aspx"

  2. 背后的代码中     受保护的字符串WindowStatusText ="&#34 ;;
    protected void Page_Load(object sender, EventArgs e)
    {
        //string RefreshValue = Convert.ToString((Session.Timeout * 60) - 60);
    
        string RefreshValue = Convert.ToString((Session.Timeout * 60) - 90);
    
        // Refresh this page 60 seconds before session timeout, effectively resetting the session timeout counter.
        MetaRefresh.Attributes["content"] = RefreshValue + ";url=KeepSessionAlive.aspx?q=" + DateTime.Now.Ticks;
    
        WindowStatusText = "Last refresh " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
    }
    
  3. 在母版页中添加隐藏的iFrame

    iframe ID =" KeepAliveFrame" SRC =" KeepSessionAlive.aspx" FRAMEBORDER =" 0"宽度=" 0"高度=" 0"

  4. Download example