Session变量产生错误
问题描述:
我将尝试使用会话,但我得到的错误:Session变量产生错误
The name 'Session' does not exist in the current context
什么我做错了,我使用的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();
}
}
答
如果你的方法是不是从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 = ...)
{
...
}
}
非常感谢你@Guffa。现在我们可以把它当作简单的Session变量吗? – 2012-01-11 08:24:50
@RaniaUmair:这与使用'Page'类中的'Session'属性访问的集合相同。它只是http上下文对象中的集合的一个捷径。 – Guffa 2012-01-11 08:46:16