How can I redirect to a page when the user session expires?

前端 未结 11 1711
我在风中等你
我在风中等你 2020-12-28 20:25

I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. T

相关标签:
11条回答
  • 2020-12-28 20:39

    You can't redirect the user when the session expires because there's no browser request to redirect:

    • If the user visits your site within the session timeout (20 minutes by default), the session hasn't ended, therefore you don't need to redirect them.
    • If the user visits your site after the session has timed out, the session has already ended. This means that they will be in the context of a new session - Session_OnEnd will already have fired for the old session and instead you'll be getting Session_OnStart for the new session.

    Other than a client-side feature (eg JavaScript timer etc), you therefore need to handle the redirect in a Session_OnStart instead - but obviously you need to distinguish this from someone coming to the site afresh. One option is to set a session cookie when their session starts (ie a cookie with no expiry so that it only lasts until the browser is closed), then look for that cookie in Session_OnStart - if it's present it is a returning user with an expired session, if not it's a new user.

    Obviously you can still use Session_OnEnd to tidy up on the server side - it's just the client interaction that isn't available to you.

    0 讨论(0)
  • 2020-12-28 20:39

    Code from here

    namespace PAB.WebControls
    

    { using System; using System.ComponentModel; using System.Web; using System.Web.Security; using System.Web.UI;

    [DefaultProperty("Text"),
    
        ToolboxData("<{0}:SessionTimeoutControl runat=server></{0}:SessionTimeoutControl>")]
    
    public class SessionTimeoutControl : Control
    {
        private string _redirectUrl;
    
        [Bindable(true),
            Category("Appearance"),
            DefaultValue("")]
        public string RedirectUrl
        {
            get { return _redirectUrl; }
    
            set { _redirectUrl = value; }
        }
    
        public override bool Visible
        {
            get { return false; }
    
        }
    
        public override bool EnableViewState
        {
            get { return false; }
        }
    
        protected override void Render(HtmlTextWriter writer)
        {
            if (HttpContext.Current == null)
    
                writer.Write("[ *** SessionTimeout: " + this.ID + " *** ]");
    
            base.Render(writer);
        }
    
    
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
    
            if (this._redirectUrl == null)
    
                throw new InvalidOperationException("RedirectUrl Property Not Set.");
    
            if (Context.Session != null)
            {
                if (Context.Session.IsNewSession)
                {
                    string sCookieHeader = Page.Request.Headers["Cookie"];
    
                    if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        if (Page.Request.IsAuthenticated)
                        {
                            FormsAuthentication.SignOut();
                        }
    
                        Page.Response.Redirect(this._redirectUrl);
                    }
                }
            }
        }
    }
    

    }

    0 讨论(0)
  • 2020-12-28 20:42

    If I understand correctly, "Session_End" fires internally and does not have an HTTP context associated with it:

    http://forums.asp.net/t/1271309.aspx

    Therefore I don't think you could use it to redirect the user. I've seen others suggest using the "Session_OnStart()" event in the global.ascx file:

    http://forums.asp.net/p/1083259/1606991.aspx

    I have not tried it, but putting the following code in "global.ascx" might work for you:

    void Session_OnStart() {
        if (Session.IsNewSession == false )
        {
        }
        else 
        {
            Server.Transfer("SessionExpired.aspx", False);
        }
    }
    
    0 讨论(0)
  • 2020-12-28 20:43

    We use Forms Authentication and call this method in the Page_Load method

    private bool IsValidSession()
        {
            bool isValidSession = true;
            if (Context.Session != null)
            {
                if (Session.IsNewSession)
                {
                    string cookieHeader = Request.Headers["Cookie"];
                    if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        isValidSession = false;
                        if (User.Identity.IsAuthenticated)
                            FormsAuthentication.SignOut();
                        FormsAuthentication.RedirectToLoginPage();
                    }
                }
            }
            return isValidSession;
        }
    
    0 讨论(0)
  • 2020-12-28 20:49

    I usually add an HtmlMeta control to the Page.Header.Controls collection on the master page when the user has "logged in". Set it to Refresh to your SessionExpired.aspx page with an appropriate timeout length, and you're good to go.

    0 讨论(0)
  • 2020-12-28 20:49

    Add or update your Web.Config file to include this or something similar:

    <customErrors defaultRedirect="url" mode="RemoteOnly">
        <error statusCode="408" redirect="~/SessionExpired.aspx"/>
    </customErrors>
    
    0 讨论(0)
提交回复
热议问题