【问题标题】:Can't detect whether Session variable exists无法检测 Session 变量是否存在
【发布时间】:2012-10-09 22:23:54
【问题描述】:

我正在尝试确定 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”不存在,但我检测不到!

【问题讨论】:

    标签: c# asp.net session session-variables nullreferenceexception


    【解决方案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

    【讨论】:

      【解决方案2】:

      如果在 Azure 上部署(截至 2017 年 8 月),还需要检查会话密钥数组是否已填充,例如:

      Session.Keys.Count > 0 && Session["company_path"]!= null
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 感谢您的回答,但我仍然遇到同样的错误
        • 检查当前线程是否可以访问 System.Web.HttpContext?
        • 如何检查?我有using System.Web?对吗?
        • 是你的aspx页面代码落后还是你库中的某个类?
        • 这是我的 App_Code 文件夹中的一个类。是否有一种特殊的方式需要我授予它访问权限?我想避免在构造函数中传递变量。谢谢:)
        猜你喜欢
        • 2017-08-05
        • 2011-08-05
        • 2014-09-08
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 2016-12-28
        • 2020-05-30
        相关资源
        最近更新 更多