无法检测Session变量是否存在

Luk*_*uke 10 c# asp.net session session-variables nullreferenceexception

我正在尝试确定Session变量是否存在,但我收到错误:

System.NullReferenceException:未将对象引用设置为对象的实例.

码:

    // Check if the "company_path" exists in the Session context
    if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null)
    {
        // Session exists, set it
        company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
    }
    else
    {
        // Session doesn't exist, set it to the default
        company_path = "/reflex/SMD";
    }
Run Code Online (Sandbox Code Playgroud)

那是因为Session名称"company_path"不存在,但我无法检测到它!

Adi*_*dil 27

如果要检查Session ["company_path"]是否为空,请不要使用ToString().如if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.

更改

if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null)
{
    company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
}
else
{
    company_path = "/reflex/SMD";
}
Run Code Online (Sandbox Code Playgroud)

if (System.Web.HttpContext.Current.Session["company_path"]!= null)
{
      company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
}
else
{
      company_path = "/reflex/SMD";
}
Run Code Online (Sandbox Code Playgroud)