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

You can handle this in global.asax in the Session_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired:

   public void Session_OnStart()
    {
        if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null)
        {
            HttpContext.Current.Response.Redirect("SessionTimeout.aspx")
        }

    }

Alas I have not found any elegant way of finding out the name of the session cookie.


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.


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

Tags:

C#

Asp.Net