会话变量生成错误

本文关键字:错误 变量 会话 | 更新日期: 2023-09-27 18:20:02

我试图使用会话,但遇到错误:

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

我做错了什么,我使用的是n-tier,在这个页面中没有页面加载功能。会话是否具有与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();
    }
}

会话变量生成错误

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

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

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

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

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 = ...)
   {
      ...
   }
}