C# 无法检测Session变量是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12971966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't detect whether Session variable exists
提问by Luke
I'm trying to determine if a Sessionvariable exists, but I'm getting the error:
我正在尝试确定Session变量是否存在,但出现错误:
System.NullReferenceException: Object reference not set to an instance of an object.
System.NullReferenceException:未将对象引用设置为对象的实例。
Code:
代码:
// 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";
}
That is because the Sessionname "company_path" doesn't exist, but I can't detect it!
那是因为Session名称“company_path”不存在,但我无法检测到它!
采纳答案by Adil
Do not use ToString() if you want to check if Session["company_path"] is null. As if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.
如果要检查 Session["company_path"] 是否为空,请不要使用 ToString()。作为if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.
Change
改变
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";
}
To
到
if (System.Web.HttpContext.Current.Session["company_path"]!= null)
{
company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
}
else
{
company_path = "/reflex/SMD";
}
回答by Manish
If deploying on Azure (as of August 2017), it is useful to also check if the Session keys array is populated, e.g.:
如果在 Azure 上部署(截至 2017 年 8 月),还可以检查会话密钥数组是否已填充,例如:
Session.Keys.Count > 0 && Session["company_path"]!= null
回答by Luke
This can be solved as a one liner in the latest version of .NET using a null-conditional ?.and a null-coalesce ??:
这可以在最新版本的 .NET 中使用 null-conditional?.和 null-coalesce作为单行解决??:
// Check if the "company_path" exists in the Session context
company_path = System.Web.HttpContext.Current.Session["company_path"]?.ToString() ?? "/reflex/SMD";
Links:
链接:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operatorhttps://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
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

