[c#] How to Check whether Session is Expired or not in asp.net

I've specified the session timeout in web.config file. When the session is timeout I'm not getting redirect to the login page but I am getting an error saying object reference not set to an instance.

Can anyone tell me the solution for this?

This question is related to c# asp.net

The answer is


You can check the HttpContext.Current.User.Identity.IsAuthenticated property which will allow you to know whether there's a currently authenticated user or not.


Edit

You can use the IsNewSession property to check if the session was created on the request of the page

protected void Page_Load() 
{ 
   if (Context.Session != null) 
   { 
      if (Session.IsNewSession) 
      { 
         string cookieHeader = Request.Headers["Cookie"]; 
         if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) 
         { 
            Response.Redirect("sessionTimeout.htm"); 
         } 
      } 
   } 
}

pre

Store Userid in session variable when user logs into website and check on your master page or created base page form which other page gets inherits. Then in page load check that Userid is present and not if not then redirect to login page.

if(Session["Userid"]==null)
{
  //session expire redirect to login page 
}

I use the @Adi-lester answer and add some methods.

Method to verify if Session is Alive

public static void SessionIsAlive(HttpSessionStateBase Session)
{
    if (Session.Contents.Count == 0)
    {
        Response.Redirect("Timeout.html"); 
    }
    else
    {
        InitializeControls();
    }
}

Create session var in Page Load

protected void Page_Load(object sender, EventArgs e)
{
    Session["user_id"] = 1;
}

Create SaveData method (but you can use it in all methods)

protected void SaveData()
{
    // Verify if Session is Alive
    SessionIsAlive(Session);

    //Save Data Process
    // bla
    // bla
    // bla
}

this way many people detect session has expired or not. the below code may help u.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

Here I am checking session values(two values filled in text box on previous page)

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
    {
        Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
    }
    else
    {

        lblUnit.Text = Session["sessUnit_code"].ToString();
        LblGrcSr.Text = Session["sessgrcSerial"].ToString();
    }
}

Use Session.Contents.Count:

if (Session.Contents.Count == 0)
{
    Response.Write(".NET session has Expired");
    Response.End();
}
else
{
    InitializeControls();
}

The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.

protected void Page_Load(object sender, EventArgs e)
{
    Session["user_id"] = 1;
}

Best of luck to you!


Check if it is null or not e.g

if(Session["mykey"] != null)
{
  // Session is not expired
}
else
{
  //Session is expired
}

I prefer not to check session variable in code instead use FormAuthentication. They have inbuilt functionlity to redirect to given LoginPage specified in web.config.

However if you want to explicitly check the session you can check for NULL value for any of the variable you created in session earlier as Pranay answered.

You can create Login.aspx page and write your message there , when session expires FormAuthentication automatically redirect to loginUrl given in FormAuthentication section

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="30">
  </forms>
</authentication>

The thing is that you can't give seperate page for Login and SessionExpire , so you have to show/hide some section on Login.aspx to act it both ways.

There is another way to redirect to sessionexpire page after timeout without changing formauthentication->loginurl , see the below link for this : http://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html