• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 359
  • Last Modified:

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
0
enrique_aeo
Asked:
enrique_aeo
  • 5
  • 3
1 Solution
 
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
 
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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:
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:
typo...  BasePageTest.aspx.cs not SamplePage.aspx.cs
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now