Object reference not set to an instance of an object session lost

Hi experts, I need to validate if a user loses the session, meaning that it redirects to the login page. I attaced the error
sinSESSION.jpg
enrique_aeoAsked:
Who is Participating?
 
guru_samiCommented:
sample here:
BasePage.cs in App_Code Folder:

using System;
using System.Web;
public class BasePage: System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {

        if (Session["userConnected"] == null)
        {
           Response.Redirect("~/login.aspx");
        }  

        base.OnLoad(e);

    }  
}

Code-behind of sample Page using BasePage:
SamplePage.aspx.cs

public partial class BasePageTest : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //This code will be reached only if Session["userConnected"] is not null
        string s = Session["userConnected"].ToString();
    }
}
0
 
guru_samiCommented:
you can put a null check on session before using it like:

if(Session["userConnected"]==null){
     Resposne.Redirect("~/login.aspx");
}
else{
//use it
}
0
 
enrique_aeoAuthor Commented:
ok, I'm using that session variable 35 times, is there another way to do it?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
guru_samiCommented:
You mean same page or different pages?
Is that going to be in a page code-behind that uses master page?
If yes, then you can do that check in your MasterPags's Page_Load..i mean then you will need an if statement.

Another option is using a BasePage: http://weblogs.asp.net/scottgu/archive/2005/08/02/421405.aspx
0
 
enrique_aeoAuthor Commented:
Interestingly, you could help me with the code of a page based on this case of the session
0
 
guru_samiCommented:
sorry, what's it that you want me to help you with?
0
 
enrique_aeoAuthor Commented:
I use a base page, if possible I want to help me with the code that should have that page to check if the session is null
0
 
guru_samiCommented:
typo...  BasePageTest.aspx.cs not SamplePage.aspx.cs
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.