代码之家  ›  专栏  ›  技术社区  ›  Coskun Ozogul

计时器发出的ajax请求是否扩展了会话?

  •  2
  • Coskun Ozogul  · 技术社区  · 6 年前

    以下是我发现的方法: 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调用会扩展会话吗?或者,由于它不是用户操作,会话最终会过期吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Seabizkit    6 年前

    这是解决方案:

       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
    {
     ...