我希望在会话超时时自动重定向到登录页面.
在web.config文件中,我有以下代码
<configuration>
<system.web>
<sessionState mode="InProc" timeout="1"/>
</system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)
在Global.asax文件中 -
protected void Session_End(object sender, EventArgs e)
{
Response.Redirect("LoginPage.aspx");
}
Run Code Online (Sandbox Code Playgroud)
但超时后,我收到以下错误:
HttpException未被用户代码处理.
在这种情况下无法获得响应.
有什么线索可以解决这个问题吗?
Session_End在会话结束时调用 - 通常在最后一次请求后20分钟(例如,如果浏览器处于非活动状态或关闭状态).
由于没有请求,也没有回应.
Application_AcquireRequestState如果没有活动会话,我建议进行重定向.请记住通过检查当前URL来避免循环.
编辑:我不喜欢.Nets内置身份验证,示例进入Global.asax:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
try
{
string lcReqPath = Request.Path.ToLower();
// Session is not stable in AcquireRequestState - Use Current.Session instead.
System.Web.SessionState.HttpSessionState curSession = HttpContext.Current.Session;
// If we do not have a OK Logon (remember Session["LogonOK"] = null; on logout, and set to true on logon.)
// and we are not already on loginpage, redirect.
// note: on missing pages curSession is null, Test this without 'curSession == null || ' and catch exception.
if (lcReqPath != "/loginpage.aspx" &&
(curSession == null || curSession["LogonOK"] == null))
{
// Redirect nicely
Context.Server.ClearError();
Context.Response.AddHeader("Location", "/LoginPage.aspx");
Context.Response.TrySkipIisCustomErrors = true;
Context.Response.StatusCode = (int) System.Net.HttpStatusCode.Redirect;
// End now end the current request so we dont leak.
Context.Response.Output.Close();
Context.Response.End();
return;
}
}
catch (Exception)
{
// todo: handle exceptions nicely!
}
}
Run Code Online (Sandbox Code Playgroud)