Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help.

Thanks!

like image 834
Fede F Avatar asked Sep 26 '08 15:09

Fede F


4 Answers

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.

like image 59
csgero Avatar answered Nov 15 '22 18:11

csgero


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.

like image 43
Pseudo Masochist Avatar answered Nov 15 '22 17:11

Pseudo Masochist


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);
    }
}
like image 31
Gabe Sumner Avatar answered Nov 15 '22 17:11

Gabe Sumner


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;
    }
like image 22
CSharpAtl Avatar answered Nov 15 '22 17:11

CSharpAtl