我正在寻找一种方法来结束我的会话,并在我的系统提供TimeOut时将用户重定向到登录屏幕。
我根据我研究的一些例子尝试使用Session.Abandon()。但我不知道我做错了什么。下面是我在Global.asax中的代码:
protected void Application_EndRequest(object sender, EventArgs e)
{
var context = new HttpContextWrapper(Context);
if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
var redirectLocation = context.Response.RedirectLocation.ToString();
context.Response.RedirectLocation = null;
context.Response.ContentType = "text/plain";
context.Response.Write("session_timeout;" + redirectLocation);
Session.Abandon();
Response.Redirect("~/Account/Login");
}
}
代码只运行到:context.Session.Abandon();除非我刷新页面,否则不会重定向到登录屏幕。
public ActionResult LogOff()
{
HttpContext.Session.Remove(SessionKeys.UserType);//This will remove all keys from session variable. For example, if your session contains id, name, phone number, email etc.
HttpContext.Session.RemoveAll();//This will remove all session from application
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
我能够这样解决我的问题:
1 - 我通过添加此标记在我的Web.config中设置超时时间:
<sessionState timeout="16"></sessionState>
2 - 我在javascript中创建了一个函数,如果超时时间结束则veridifca:
var sessionTimeoutWarning = @Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
alert("Your session has expired");
window.location = "/Account/SessionTimeOutLogOff";
}
注意:此函数放在我的_Layout.chshtml中