[英]Check for Session before returning it?
大家好,我在实用程序类中有一个函数,该函数返回当前会话的用户ID。 它抛出未设置为object实例的对象引用吗? 如何检查它是否为空并删除此错误?
public static string GetSessionUserID
{
get
{
string userID = "";
if (System.Web.HttpContext.Current.Session["userID"].ToString() != null)
{
userID = System.Web.HttpContext.Current.Session["userID"].ToString();
}
if (userID == null)
{
throw new ApplicationException("UserID is null");
}
else
return userID;
}
}
object userID = System.Web.HttpContext.Current.Session["userID"];
if (userID == null)
{
throw new ApplicationException("UserID is null");
}
return userID.ToString();
如果存储在会话中的对象实际上已经是字符串,则可以省去ToString
。 错误的原因很简单,您不能在空引用上调用ToString
。 这就是上述检查之前要进行检查的原因。
使用“尝试”而不是“如果”
string userID = "";
try{
userID = System.Web.HttpContext.Current.Session["userID"].ToString();
}
catch{
throw new ApplicationException("UserID is null");
}
return userID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.