代码之家  ›  专栏  ›  技术社区  ›  Zo Has

在返回会话之前检查会话?

  •  1
  • Zo Has  · 技术社区  · 14 年前

    大家好,我在一个实用程序类中有一个函数,它返回当前会话用户ID。 它是否引发未设置为对象实例的对象引用?如何检查它是否为空并删除此错误?

    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;
        }
    }
    
    2 回复  |  直到 14 年前
        1
  •  6
  •   Matthew Flaschen    14 年前
    object userID = System.Web.HttpContext.Current.Session["userID"];
    if (userID == null)
    {
        throw new ApplicationException("UserID is null");
    }
    return userID.ToString();
    

    如果存储在会话中的对象实际上已经是一个字符串,则可以免除 ToString . 错误的原因就是你不能打电话 弦线 在空引用上。这就是为什么在这样做之前要进行上述检查。

        2
  •  0
  •   D.J    14 年前

    使用“try”而不是“if”

    string userID = "";
    try{
                userID = System.Web.HttpContext.Current.Session["userID"].ToString();
    }
    catch{
                throw new ApplicationException("UserID is null");
    }
    return userID;