会话变量生成错误

时间:2012-01-11 08:16:11

标签: c# asp.net .net session .net-2.0

我正在尝试使用会话,但我收到错误:

  

当前上下文中不存在名称“会话”

我做错了我正在使用n层,在这个页面中没有页面加载功能。会话与page_load有关联吗?

public bool CheckDate(ArrayList roles, string username, string password, string locat)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN"].ToString());
    SqlCommand chkdt = new SqlCommand("AccountRoles_GetDateForID", conn);
    chkdt.CommandType = CommandType.StoredProcedure;
    chkdt.Parameters.Add(new SqlParameter("@userName", SqlDbType.VarChar, 32));
    chkdt.Parameters["@userName"].Value = username;
    chkdt.Parameters.Add(new SqlParameter("@password", SqlDbType.VarChar, 250));
    chkdt.Parameters["@password"].Value = password;
    chkdt.Parameters.Add(new SqlParameter("@location", SqlDbType.VarChar, 50));
    chkdt.Parameters["@location"].Value = locat;
    conn.Open();
    try
    {
        DateTime ddt = new DateTime();
        DateTime tdd = DateTime.Parse(DateTime.Now.ToShortDateString());
        SqlDataReader reader = chkdt.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                if (reader["ExpiryDate"].ToString() == "")
                {
                }
                else
                {
                    ddt = DateTime.Parse(reader["ExpiryDate"].ToString());
                }
            }
        }
        TimeSpan ts = ddt.Subtract(tdd);
        day = ts.Days.ToString();
        Session["days"] = day;
        if (tdd.Equals(ddt))
        {               
            return true;
        }
        else
        {
            return false;
        }
    }
    finally
    {
        conn.Close();
        chkdt.Dispose();
    }
}

2 个答案:

答案 0 :(得分:2)

如果您的方法不在继承自Page的类中,则不会继承Session属性。

使用Current类的HttpContext属性访问Session集合所在的当前http上下文:

HttpContext.Current.Session["days"] = day;

答案 1 :(得分:1)

无论如何,您可以使用以下技巧缩短代码:

chkdt.Parameters.Add("@userName", SqlDbType.VarChar, 32).Value = username;
chkdt.Parameters.Add("@password", SqlDbType.VarChar, 250).Value = password;
chkdt.Parameters.Add("@location", SqlDbType.VarChar, 50).Value = locat;

不要两次读取数据阅读器:

DateTime? dt = reader["ExpiryDate"] as DateTime?; // if column has DateTime-compatible type
if (dt.HasValue)
{
}
else
{
}

关闭数据阅读器。甚至可以更好地将所有内容包装在使用块中:

using (SqlConnection conn = ...)
using (SqlCommand chkdt = ...)
{
   ...
   using (SqlDataReder reader = ...)
   {
      ...
   }
}
相关问题