我有一个带有 Windows 身份验证
的 MVC4 应用程序。用户可以输入 10 个 View 中任意一个的 url 来加载应用程序。没有具体的主页
如果用户空闲时间超过一分钟,我需要重定向到 session 超时 View 。我将配置文件中的 session 超时值保留为一分钟。我创建了一个操作过滤器
来检查一个特定的 session 值。此特定 session 值在 Global.asax
的 Session_Start
中设置。
但是,当超时时间结束时,请求再次到达 Session_Start
并且正在分配值。因此,我的操作过滤器不会重定向到错误 View 。
有哪些可能的解决方案可以克服这个问题?
Web.Config
<system.web>
<!--Impersonate-->
<identity impersonate="true"/>
<!--Session Mode and Timeout-->
<sessionState mode="InProc" timeout="1" />
<authentication mode="Windows">
</authentication>
<authorization>
<allow users="?" />
</authorization>
</system.web>
Action 过滤器
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class SessionCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
HttpSessionStateBase session = filterContext.HttpContext.Session;
var activeSession = session["IsActiveSession"];
if (activeSession == null)
{
//Redirect
var url = new UrlHelper(filterContext.RequestContext);
var loginUrl = url.Content("~/Error/SessionTimeout");
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
Global.ASAX
protected void Session_Start(object sender, EventArgs e)
{
Session["IsActiveSession"] = DateTime.Now;
}
最佳答案
无需设置 session 值并在操作过滤器中检查它,只需检查 HttpContext.Current.Session.IsNewSession
查看是否为当前请求创建了新 session 。修改你的 Action 过滤器,你最终会得到这样的结果:
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class SessionCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
HttpSessionStateBase session = filterContext.HttpContext.Session;
if (session.IsNewSession)
{
//Redirect
var url = new UrlHelper(filterContext.RequestContext);
var loginUrl = url.Content("~/Error/SessionTimeout");
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
如果您想要奇特并确保他们在为此请求创建的新 session 之前有一个先前的 session ,您可以更新 if
用于检查旧 session cookie 是否随请求一起发送的语句:
string cookieHeader = filterContext.HttpContext.Request.Headers["Cookie"];
if (session.IsNewSession && cookieHeader != null && cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
{
...
}
但由于看起来您正在将它们发送到登录页面,因此您可能不必在这里担心。如果您确实使用此检查,请注意此代码假定默认值 "ASP.NET_SessionId"
cookie 名称;这可以在您的 web.config 中更改,在这种情况下您需要更新 IndexOf
带有新 cookie 名称或 get the cookie name programmatically 的参数.
关于asp.net-mvc - 用于 session 超时处理的 session 启动和操作过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19332053/