首页 > 解决方案 > 计时器完成的 ajax 请求是否会延长会话?

问题描述

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

这是我发现的:如何在计时器 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 调用会扩展会话还是因为它不是用户操作,所以会话将在最后过期?

标签: jqueryajaxasp.net-mvc-5

解决方案


这是解决方案:

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

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

推荐阅读