Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP / C# Session Variable - Object reference not set to an instance of an object

I'm somewhat new to ASP / C# and I'm having an issue (probably simple) with sessions variables. My project has a Site.Master in which session variables are set under the Page_Load method like so:

    protected void Page_Load(object sender, EventArgs e)
    {

        if ((Session)["UserID"]==null || (Session)["UserID"].ToString() == "")
        {
            (Session)["UserID"] = HttpContext.Current.User.Identity.Name.ToString();
            SqlDataReader dr = Sprocs.GetPermissionGroups();

            string groupList = "";

            while (dr.Read())
            {
            if (groupList != "")
                    {
                        groupList = groupList + "|" + dr["WG_Group"].ToString();
                    }
                    else
                    {
                        groupList = dr["WG_Group"].ToString();
                    }
            }
            dr.Close();

            if (groupList != "")
            {
                (Session)["UserGroups"] = groupList;
            }
        }

This does work. If I dump out the session variable 'UserGroups' to a label or something within this method, it does display the variable contents correctly.

So, my problem lies within another page (say default.aspx) when I try to access that same session variable. In the Page_Load method of the other page I attempt to do this:

    protected void Page_Load(object sender, EventArgs e)
    {
            string GroupList = HttpContext.Current.Session["UserGroups"].ToString();
            //some code with the variables here
    }

This always fails with an "Object reference not set to an instance of an object." error. Am I trying to get the Session variable wrong? I've tried

string GroupList = Session["UserGroups"].ToString(); 

this also errors with the same error.

string GroupList = (string)(Session["UserGroups"]); 

This always returns an empty string.

What am I doing wrong?

Thanks!

like image 204
Seril Avatar asked Dec 29 '11 15:12

Seril


Video Answer


1 Answers

The syntax you are using in your Page_Load method I wouldn't have even expected to compile. Regardless, the issue is that you have not set the Session with that key, so it will return null. When you call ToString() on that null, you get the exception. In your second example:

string groupList = (string)(Session["UserGroups"])

That is doing a conversion of null to string, which results in a null string (thus not causing the exception).

You should be able to rewrite your Page_Load implementation like so:

string sessionUserId = Session["UserId"] as string;

if(string.IsNullOrEmpty(sessionUserId))
{
    Session["UserId"] = HttpContext.Current.User.Identity.Name.ToString();

    SqlDataReader dr = Sprocs.GetPermissionGroups();

    string groupList = "";

    while (dr.Read())
    {
        if (groupList != "")
        {
            groupList = groupList + "|" + dr["WG_Group"].ToString();
        }
        else
        {
            groupList = dr["WG_Group"].ToString();
        }
    }
    dr.Close();

    Session["UserGroups"] = groupList;
}

Then, when accessing the session variable later, do it like so:

 string userGroup = Session["UserGroups"] as string;

This is a safe way to attempt the conversion of whatever bucket that is in session into a string. If the key doesnt exist, or the value is not a string, you will get null. Otherwise, you will get the string from that hash.

like image 119
Tejs Avatar answered Sep 18 '22 00:09

Tejs