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!
The syntax you are using in your
Page_Loadmethod 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 returnnull. When you callToString()on that null, you get the exception. In your second example: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_Loadimplementation like so:Then, when accessing the session variable later, do it like so:
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.