tags:

views:

125

answers:

3

Hi,

Can anyone tell me how to detect when a users session has exipred in asp?

I want to redirect users to a logged out page once the session has expired

Thanks Sp

A: 

Use the Session_End() function in your global.asax file. Please see here for more info

SO - Session End

EDIT: Nope, that probably won't do it. See comments below.

If you must redirect on a session expiration, would something like this do the trick for you?

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”);

}

EDIT 2: Caveat, this can get tricky if you have AJAX stuff going on.

I have seen examples where people will put this in the page_load of a base page and inheirit all of your .aspx pages from this base page. This prevents you from having to add this code for every single page that you have.

Why won't the first method work (Session_End)? This is a function called internally on the server when a session ends. As such, there is no associated request/response to redirect or transfer. I.e., this function could be called by the server 20 minutes after you close the browswer.

Tommy
@Tommy: Session_End is for cleaning up session variables not for Redirecting user to any other page.
Amitabh
@Amitabh I thnk he mean the function in the global.aspx
Steven
No, he is right, my bad. Updated post with another solution.
Tommy
+1  A: 

If you are using Asp.Net Forms Authentication then the user will be automatically redirected to the login page if the user session has expired.

You can also check httpcontext.user.identity.isauthenticatedat Application_BeginRequestin Global.asax

Amitabh
A: 

I suppose you have to implement the session check on a group of pages of your site, so a good way to do that is to declare a base class for all your "restricted access" pages. Something like:

public class BasePage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (Session["Context"] == null) 
        {
            // do redirect
        }
    }
}

supposing that, on login, you'll assign an object representing the session to Session["Context"]

Your pages will inherit this class as:

public partial class _Default : BasePage { ... }
tanathos