无法检测Session变量是否存在

时间:2012-10-19 10:08:51

标签: 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";
    }

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

2 个答案:

答案 0 :(得分:25)

如果要检查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";
}

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

答案 1 :(得分:1)

可以使用空条件?.和空行??作为最新版.NET中的一个衬套来解决:

// Check if the "company_path" exists in the Session context
company_path = System.Web.HttpContext.Current.Session["company_path"]?.ToString() ?? "/reflex/SMD";

链接:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators