Redirecting to another page on Session_end event

前端 未结 7 1400
心在旅途
心在旅途 2020-12-03 06:13

I would like to auto-redirect to login page when session time outs.

In web.config file, i have the following code


    

        
7条回答
  •  暖寄归人
    2020-12-03 06:27

    Session_End is called when the session ends - normally 20 minutes after the last request (for example if browser is inactive or closed).
    Since there is no request there is also no response.

    I would recommend to do redirection in Application_AcquireRequestState if there is no active session. Remember to avoid loops by checking current url.

    Edit: I'm no fan of .Nets built in authentication, Example goes in 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!
            }
        }
    

提交回复
热议问题