无法检测Session变量是否存在
我正在尝试确定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”不存在,但我无法检测到它!
如果要检查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"; }
如果在Azure上部署(截至2017年8月),还要检查是否填充了会话密钥数组,例如:
Session.Keys.Count > 0 && Session["company_path"]!= null
这可以使用null条件?.
在最新版本的.NET中作为一个内核来解决?.
和null-coalesce ??
:
// 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 /运营/空条件,运营商