We often get forum posts here asking "How can I tell if a user's Session is timed out, and perform some action in response?" Often this involves the incorrect assumption that the Session_End event can be used for this. ASP.NET implements a rolling timeout mechanism that extinguishes the session information for a user if no request is received within the timeout period. Session_End happens on the server automatically regardless of whether a user has requested a page, so the idea of using it to do anything other than cleanup-type operations is a mistake; it is independent of the page lifecycle and there is no active Request or Response object to access there.
It is often important for the business logic of an ASP.NET site to know for a particular request if the user’s session information is valid (e.g., a timeout has not occurred). Without this technique it is difficult to know, when a session variable is not found, whether it was never set properly or that the user simply waited too long between requests.  Logic normally dictates that if a session is expired, any saved state needs to be recycled back to its starting state, and typically the user should also be required to re-authenticate to the site in order to enable them to start whatever process they abandoned again from the beginning.
ASP.NET developers habitually reference Session variables without ever checking for null first to see if they are actually present,  which causes the "Object reference not set" exception. That yellow error page doesn't look very professional to the user, either.
So, I set out to do some more research and see what solutions might be possible. One of the ideas I got was that a site-wide session-expiry mechanism might be overkill, since usually only certain pages (such as those involved in a shopping cart) are involved in the need for protection against expired sessions. That's what brought me to think of the idea of a "drop on the page" Session Timeout "Detect and Redirect" Control. You should be able to just drop it on the pages that need it, set the redirect url, and you would be "good to go". (I should add here that based on some reader confusion in the posts below, if you do not need a page-specific solution, you can just use the Base Page class approach, or if you don't want to use a base Page class, instead you could write an HttpModule to do this and register it in web.config.)
The only credible information I found came from a source whose work I have relied on before, Robert Boedigheimer. Robert's original article about this may be viewed here. In sum, what Robert found was that the ASP.NET HttpSessionState class's IsNewSession( ) method returns true if a new session was created for a given request.  If this is a new session but the ASP.NET_SessionId cookie is present, this indicates a timeout situation. You may need to think about this for a while, but eventually the logic should make sense. In addition, he determined that one must access this cookie from the Request Headers collection rather than the expected Cookie collection. This is because the intrinsic Response.Cookies and Request.Cookies objects actually share the same collection, and in this test we only want to inspect the actual cookie from the Request Headers.
With this information in hand, it was very easy to create a "non-visible" ASP.NET Server control that would hook and override a late Page LifeCycle event, PreRender, to perform this check. Add a public property for the RedirectUrl, call SignOut on any Forms Authentication to force the user to login to the site over again, and send them to the login page. Let's take a look at the code for the control:
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>")]
    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);
                    }
                }
            }
        }
    }
}
In the OnPreRender event, we let the page control tree do it's thing first, then we do ours. First I check to see if the developer forgot to set the RedirectUrl property on the Control, because without that we would be all dressed up with no place to go. Then we check to see if there is actually a Session, and if so, we check the IsNewSession property. If it is true, we need to check our cookie, so we strip it out of the Request's Headers Collection and test for the "ASP.NET_SessionId" standard cookie name. If the sCookieHeader string is not null and the "ASP.NET_SessionId" cookie name is there, we know we have a timeout situation for this user. First we check to see if Authentication is being used and call the Forms SignOut method. This will ensure that the user must re-authenticate. Finally, we redirect the user to the specified redirect page on the site.
The beauty of this arrangement is that it requires no base page class to inherit from; you simply drop the control onto any page that needs to be involved in this process. Not only that, but because there is a separate instance of the control on each page that needs it, you could even have more than one RedirectUrl depending on the particular business logic, each presenting different information to the user. The downloadable solution below contains the source code and project for the Control, as well as a test web project with a starting page (that has the control) and a redirect page. The Session Timeout in the web.config is set to 1 minute so you can easily test it. This should work equally well in Visual Studio 2005 with ASP.NET 2.0.

by Peter A. Bromberg, Ph.D.

0 nhận xét:

 

Coding experience share Copyright © 2010 | Designed by Ipietoon for Free Blogger Template