如何在.net c中检查会话是否存在或者是空值还是null

时间:2022-09-24 07:21:52

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?

有谁知道如何在.net c#web-applications中检查会话是空还是空?

Example:

I have the following code:

我有以下代码:

 ixCardType.SelectedValue = Session["ixCardType"].ToString();

It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??

它始终显示Session [“ixCardType”]的错误(错误消息:对象引用未设置为对象的实例)。无论如何,我可以在转到.ToString()之前检查会话。

3 个解决方案

#1


20  

Something as simple as an 'if' should work.

像'if'这样简单的东西应该有效。

 if(Session["ixCardType"] != null)    
     ixCardType.SelectedValue = Session["ixCardType"].ToString();

Or something like this if you want the empty string when the session value is null:

如果你想在会话值为null时想要空字符串,那么就是这样:

ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();

#2


14  

Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.

使用as运算符强制转换对象,如果值无法转换为所需的类类型,则返回null,或者它本身为null。

string value = Session["ixCardType"] as string;

if (String.IsNullOrEmpty(value))
{
    // null or empty
}

#3


1  

You can assign the result to a variable, and test it for null/empty prior to calling ToString():

您可以将结果分配给变量,并在调用ToString()之前将其测试为null / empty:

var cardType = Session["ixCardType"];
if (cardType != null)
{
    ixCardType.SelectedValue = cardType.ToString();
}

#1


20  

Something as simple as an 'if' should work.

像'if'这样简单的东西应该有效。

 if(Session["ixCardType"] != null)    
     ixCardType.SelectedValue = Session["ixCardType"].ToString();

Or something like this if you want the empty string when the session value is null:

如果你想在会话值为null时想要空字符串,那么就是这样:

ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();

#2


14  

Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.

使用as运算符强制转换对象,如果值无法转换为所需的类类型,则返回null,或者它本身为null。

string value = Session["ixCardType"] as string;

if (String.IsNullOrEmpty(value))
{
    // null or empty
}

#3


1  

You can assign the result to a variable, and test it for null/empty prior to calling ToString():

您可以将结果分配给变量,并在调用ToString()之前将其测试为null / empty:

var cardType = Session["ixCardType"];
if (cardType != null)
{
    ixCardType.SelectedValue = cardType.ToString();
}