asp.net – Access Session Variable created in page from MasterPage – Education Career Blog

I am creating some sessions on successful login and I need to access them from my master page. How do I go about this?

public void showUser()
{
    if (!string.IsNullOrEmpty(Session"User".ToString()))
    {
        Response.Write(Session"User".ToString());
    }
    else
    {
        Response.Write("Not Logged In");
    }
}

,

The line (!string.IsNullOrEmpty(Session"User".ToString())) is incorrect way and will certainly raise an exception is you don;t have session variable set. Because in such case, Session”User” will return null value, so you should be checking against that.

i.e.

if (null != Session"User") 
{

Or

user = Session"User";
if (null != user && user.ToString().Length > 0)
{
  // user logged in
}
else
{
  // not logged in
}

Leave a Comment