【问题标题】:Does an ajax request done by a timer extend the session?计时器完成的 ajax 请求是否会延长会话?
【发布时间】:2019-02-24 13:02:54
【问题描述】:

在我的 Asp.Net MVC 应用程序中,如果会话过期,我想隐藏购物车和一些按钮。

这是我发现的:How to call function on timer ASP.NET MVC

window.setInterval(function() {
  // Send an AJAX request every 5s to poll for changes and update the UI
  // example with jquery:
  $.get('/foo', function(result) {
    // TODO: use the results returned from your controller action
    // to update the UI
  });
}, 5000);

问题是关于这种类型的 ajax 调用对会话的影响。 这样的 ajax 调用是否会延长会话,或者由于它不是用户操作,会话将在最后过期?

【问题讨论】:

  • 是的,发送请求会延长会话,所以这种模式是有缺陷的。
  • 我不知道我是否应该再问一个问题。在这种情况下,有没有办法定期检查会话是否过期?
  • stackoverflow.com/questions/3877646/… 看来您可以通过删除标头来删除此功能。但我不确定是什么标题,因为链接问题的 OP 删除了所有标题。
  • 感谢cmets,我要试试你的文章。我发现了这个:codeproject.com/Questions/457540/… 如果我找到解决方案,我会更新我的问题。
  • 是的,这就是我想说的,但我不清楚 :) 谢谢。如果我找到它,我将发布解决方案作为答案。

标签: jquery ajax asp.net-mvc-5


【解决方案1】:

这里是解决方案:

在我的应用程序中添加了这个类:

   using System;
   using System.Web;
   using System.Web.Mvc;
   using System.Web.Security;

namespace Capron.MVC.Filters
{
   [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
   public class SessionExpireFilterAttribute : ActionFilterAttribute
   {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
        if (filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower() == "home" 
            && (filterContext.ActionDescriptor.ActionName.ToLower() == "index" 
            || filterContext.ActionDescriptor.ActionName.ToLower() == "ındex")) {
            base.OnActionExecuting(filterContext);
            return;
        }
        HttpContext ctx = HttpContext.Current;
        if (ctx.Session != null)
        {
            if (ctx.Session.IsNewSession)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if (sessionCookie != null && sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)
                    {
                        filterContext.HttpContext.Response.StatusCode = 401;
                        filterContext.HttpContext.Response.End();
                    }
                }
                else
                {
                    ctx.Response.Redirect("~/Home/Index");
                }
            }
        }
         base.OnActionExecuting(filterContext);
      }
   }
}

并将这个属性添加到我的控制器中:

[SessionExpireFilterAttribute]
public class HomeController : BaseController
{
 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2021-12-06
    • 2012-02-09
    • 2015-09-08
    • 2010-10-15
    相关资源
    最近更新 更多