无法检测会话变量是否存在 [英] Can't detect whether Session variable exists
本文介绍了无法检测会话变量是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试确定 Session
变量是否存在,但出现错误:
I'm trying to determine if a Session
variable exists, but I'm getting the error:
System.NullReferenceException:对象引用未设置为对象的实例.
System.NullReferenceException: Object reference not set to an instance of an object.
代码:
// 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"不存在,但我无法检测到它!
That is because the Session
name "company_path" doesn't exist, but I can't detect it!
推荐答案
如果要检查Session ["company_path"]是否为空,请不要使用ToString().由于如果Session ["company_path"]为null,则Session ["company_path"].ToString()将给您例外.
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.
更改
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";
}
这篇关于无法检测会话变量是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文