【问题标题】:Check for Session before returning it?在返回之前检查会话?
【发布时间】:2010-09-08 04:19:42
【问题描述】:

大家好,我在实用程序类中有一个函数,它返回当前会话用户 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;
    }
}

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:
    object userID = System.Web.HttpContext.Current.Session["userID"];
    if (userID == null)
    {
        throw new ApplicationException("UserID is null");
    }
    return userID.ToString();
    

    如果存储在会话中的对象实际上已经是一个字符串,则可以省略ToString。错误的原因仅仅是您不能在空引用上调用ToString。这就是为什么在这样做之前进行上述检查的原因。

    【讨论】:

    • 谢谢马修。解释真的很有帮助。你的意思是 object 而不是 var ?
    • @Popo,它们应该是等价的(编译器会将var 替换为object)。不过,我同意object 在这里更清楚。
    • 谢谢你,马修。我预先。以为 var 只存在于 javascript 中。
    【解决方案2】:

    使用“尝试”而不是“如果”

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2023-03-03
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多