正在重定向到Session_end事件的另一个页面

本文关键字:事件 另一个 end 重定向 Session | 更新日期: 2023-09-27 18:30:01

我想在会话超时时自动重定向到登录页面。

在web.config文件中,我有以下代码

<configuration>
    <system.web>
       <sessionState mode="InProc"  timeout="1"/>
    </system.web>
</configuration>

在Global.asax文件-中

protected void Session_End(object sender, EventArgs e)
{
    Response.Redirect("LoginPage.aspx");
}

但超时后,我收到以下错误:

用户代码未处理HttpException。

响应在此上下文中不可用。

有解决这个问题的线索吗?

正在重定向到Session_end事件的另一个页面

Session_End在会话结束时调用,通常是在最后一次请求后20分钟(例如,如果浏览器处于非活动状态或关闭状态)
由于没有请求,因此也没有响应。

如果没有活动会话,我建议在Application_AcquireRequestState中执行重定向。记住通过检查当前url来避免循环。

编辑:我不喜欢.NET内置身份验证,示例在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!
        }
    }

如果您正在使用类似FormsAuthentication的东西来维护应用程序的安全性,那么这部分(您正在尝试做的部分)将为您完成。如果FormsAuthentication发现用户的会话已过期,它会将用户重定向回您的登录页面。

其次,不要过于依赖Session_End,因为如果您将会话提供程序从InProc更改为SQLServer或其他进程外提供程序,它将永远不会触发。

您可以使用会话属性IsNewSession来检测是否为会话超时。

ASP.NET HttpSessionState类具有IsNewSession()方法,如果为此请求创建了新会话,该方法将返回true。检测会话超时的关键是还要在请求中查找ASP.NET_SessionId cookie。

我当然也同意,我们应该把下面的代码放在一些所谓的自定义BasePage中,所有页面都使用它,以有效地实现这一点。

override protected void OnInit(EventArgs e)
  {
       base.OnInit(e);   
if (Context.Session != null)
   {
if (Session.IsNewSession)
    {
     string CookieHeader = Request.Headers["Cookie"];
     if((CookieHeader!=null) && (CookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
     {
      // redirect to any page you need to
      Response.Redirect("sessionTimeout.aspx");
     } 
   }
 }
}

如果您想将上面的代码放在一个基类中,请查看此链接以获得更多解释。

您应该使用Application_AcquireRequestState您会发现Application_AuthenticateRequest不再有会话上下文(或从未有过会话上下文)。在我对此的研究中,我偶然发现了这篇为我解决问题的帖子。感谢Waqas Raja。

asp.net:将没有会话的用户重定向到主页的代码放在哪里?

我认为您得到的是"响应在此上下文中不可用",因为用户没有向服务器发出请求,因此您无法向其提供响应。请尝试服务器。改为传输。

我觉得最简单的方法是使用元信息并使技巧发挥作用。假设我们有一个页面WebPage.aspx,在WebPage.aspx.cs文件中添加以下代码。

private void Page_Load(object sender, System.EventArgs e){      
    Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));      
    if(Session[“IsUserValid”].ToString()==””)              
    Server.Transfer(“Relogin.aspx”);
}

在上面的代码中,一旦会话过期,WebPage.aspx将在5秒后刷新。在页面加载中,会话被验证,因为会话不再有效。页面将重定向到"重新登录"页面。每次返回服务器的帖子都会刷新会话,并且会在WebPage.aspx的元信息中更新。

您可以在web.config 中简单地执行以下操作

<configuration>
<system.web>
<sessionState mode="InProc"  timeout="1" loginurl="destinationurl"/>
</system.web>
</configuration>

由于,我们无法从Session_End重定向,因为那里没有响应/重定向。当会话超时时,您将被重定向到destinationurl。希望这能有所帮助。