jquery - 计时器完成的 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 调用会扩展会话还是因为它不是用户操作,所以会话将在最后过期?
解决方案
这是解决方案:
在我的应用程序中添加了这个类:
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
{
...
推荐阅读
- python - 将多个命令写入子进程
- discord.js - guild.createChannel 不起作用,我不知道为什么
- java - Android onBackPressed 适用于所有活动
- javascript - 错误:拒绝在框架中显示“https://beta.app.com”,因为它将>“X-Frame-Options”设置为“sameorigin”
- java - 如果不是,我该如何优化以下内容?
- ios - iOS 13 导航栏样式:设备和模拟器之间的巨大差异
- pandas - 基于条件的随机数据生成 pandas 和 numpy
- php - 如何使用按日期和用户名分隔的while循环添加列的不同值(行)
- css - SCSS:更改父母的另一个孩子的可见性
- math - 查找涉及对数总和的大 O