34

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?

mvermand
  • 5,829
  • 7
  • 48
  • 74
user1379439
  • 359
  • 1
  • 3
  • 4
  • 2
    Post your code. How are you checking for session expiration? – Oded May 07 '12 at 10:01
  • Share your web config as well – Deepesh May 07 '12 at 10:01
  • Two different things: Sessions don't affect authentication state directly. If you're using FormsAuth, your ticket state does. So if you need to couch the validity of your ticket in the state of the session (which is a bad idea, BTW), you'll need manage that manually. – moribvndvs May 07 '12 at 10:05
  • 1
    You'll only be redirected for a secured page... – H H May 07 '12 at 10:05
  • This answer offers some ways to check, especially if you're site is failing PEN tests: https://stackoverflow.com/questions/31565632/invalidate-aspx-authentification-cookie – Tyler S. Loeper Mar 19 '18 at 19:16

8 Answers8

20

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.

Matt
  • 23,363
  • 39
  • 111
  • 152
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 9
    Is the expiration of the session completely synonymous with the `IsAuthenticated` changing to false? – toddmo Mar 04 '15 at 23:22
  • 3
    Whether a first time visitor or a timed out user, `HttpContext.User.Identity` will have the same values. – Bardicer Mar 29 '16 at 16:20
18

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 
}
DreamTeK
  • 32,537
  • 27
  • 112
  • 171
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • Thank You...but this can be used for only one Session value..i ve used more sessions in my project so i want code specified in web.config file...which applies to all pages – user1379439 May 07 '12 at 10:05
  • @user1379439 - this will work for all session not for single .....session get created as use log into system...what else you want ? you have idea about session right ? – Pranay Rana May 07 '12 at 10:09
  • @user1379439 - go to this url you might get what you want ...http://www.google.co.in/url?q=http://www.codeproject.com/Articles/227382/Alert-Session-Time-out-in-ASP-Net&sa=U&ei=LLKnT8PeMpDzrQe3itHRAQ&ved=0CBIQFjAA&sig2=NDlgZI2yyYDIaQ3C1E-hgA&usg=AFQjCNF-3O2DlOTaG5dmjBsFqR63vmh2WQ – Pranay Rana May 07 '12 at 11:31
  • -Since i am using this website for the first time .i dint know about marking the answers – user1379439 May 07 '12 at 11:49
  • This doesn't work for me in Chrome because `cookieHeader` already has a value on application startup and acts like there is already a timeout. In IE this works fine as `cookieHeader` is `null` on application start. Any ideas on how to handle this for Chrome? – atconway Sep 19 '13 at 20:35
  • 1
    @PranayRana, why have you suggested that Edited answer? is there any drawback in the "pre" answer? actually I have been using the "pre" one from 1 year in one web application and have been suffering from sporadic logouts to session expired page, users claims that they were even active when application kick them out, pulling my hair on this from quite some time. I'm gonna try the edited version but if you have some advice for me I'm all ears :) – yogi Aug 27 '15 at 10:08
9

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

Imran Rizvi
  • 7,331
  • 11
  • 57
  • 101
  • Thank you..i got the Session Expiry code...Now i want the message should be displayed or an alert message when the Session Expires to User...Do u know the code for this? – user1379439 May 07 '12 at 11:07
7

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!

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Brian
  • 93
  • 5
6

Check if it is null or not e.g

if(Session["mykey"] != null)
{
  // Session is not expired
}
else
{
  //Session is expired
}
Adil
  • 146,340
  • 25
  • 209
  • 204
2

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
}
equiman
  • 7,810
  • 2
  • 45
  • 47
2

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");
                    }
                }
            }
        }
    }
Mou
  • 15,673
  • 43
  • 156
  • 275
1

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();
    }
}
Ravi
  • 1,744
  • 2
  • 20
  • 37