12

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!

Fede F
  • 143
  • 2
  • 6

11 Answers11

5

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.

Pseudo Masochist
  • 1,927
  • 14
  • 12
  • What if the session expires because of any other reason than timeout? Is this possible? – Fede F Sep 26 '08 at 16:23
  • Expiration implies timeout. You can lose the session programmatically (Session.Abandon()) or if the user tampered with or removed their session cookie, but at that point the session hasn't really *expired*, per se. Maybe I'm not understanding the issue fully... – Pseudo Masochist Sep 26 '08 at 16:41
  • What if the user spends a lot of time on the same page doing stuff that uses ajax rather than standard GET/POST stuff? with this method they will still potentially be logged out. – DavidWainwright Jan 27 '12 at 16:14
5

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.

csgero
  • 2,753
  • 17
  • 15
  • I've accepted this answer because the key of identifying an expired session is to check if the session cookie exists when dealing with a new session. – Fede F Sep 26 '08 at 17:57
  • Unfortunately there is no nice way of getting the session cookie name because you can't do "Session.CookieName" like you can with the FormsAuthneticationTicket. The best recommendation I have found is to just have an appSetting key/value that will hold the name of the Session Cookie. So you will be setting it twice, which no one likes doing, but seems like the most convenient way to do it. Just my two cents. – dyslexicanaboko Dec 22 '11 at 17:08
4

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);
    }
}
Gabe Sumner
  • 4,978
  • 6
  • 33
  • 43
3

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;
    }
CSharpAtl
  • 7,374
  • 8
  • 39
  • 53
2

The other way is to tell the browser to redirect itself (via javascript) after a certain amount of time... but that can always be deactivated by the user.

Pablo Marambio
  • 1,562
  • 1
  • 15
  • 29
1

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.

Simon Forrest
  • 2,327
  • 18
  • 22
1

Are you putting something in the Session object that should always be there? In other words, if they log in, you may be putting something like UserID in the session

Session("UserID") = 1234

So, if that is the case, then you could add something to your codebehind in the master page that checks for that value. Something like this:

Dim UserID As Integer = 0
Integer.TryParse(Session("UserID"), UserID)

If UserID = 0 Then
  Response.Redirect("/sessionExpired.aspx")
End If
Micky McQuade
  • 1,873
  • 1
  • 16
  • 21
  • Mmmm...that almost work. But I have one problem. Users don't login. Instead, Windows authentication is used. Anyway I'm using this solution with a redirect to the main page while I find a final solution. – Fede F Sep 26 '08 at 17:14
1

You can also check the solutions provided in below link

Detecting Session Timeout And Redirect To Login Page In ASP.NET

Avdhoota
  • 451
  • 4
  • 20
0

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>
wprl
  • 24,489
  • 11
  • 55
  • 70
0

Are you looking to redirect on the next request, or redirect immediately, without user intervention? If you're looking to redirect without user intervention, then you can use ClientScript.RegisterStartupScript on your Master Page to inject a bit of javascript that will redirect your clients when their session expires.

    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    String timeoutPage = "SessionExpired.aspx"; // your page here
    int timeoutPeriod = Session.Timeout * 60 * 1000;

    sb.AppendFormat("setTimeout(\"location.href = {0};\",{1});", timeoutPage, timeoutPeriod);
    Page.ClientScript.RegisterStartupScript(this.GetType(), "timeourRedirect", sb.ToString(), true);
Jeremy Frey
  • 2,334
  • 2
  • 22
  • 26
0

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

}

TheEmirOfGroofunkistan
  • 5,476
  • 8
  • 37
  • 53