C# 会话变量生成错误
我正在尝试使用会话,但出现错误: 当前上下文中不存在名称“会话” 我做错了什么,我使用的是n层,在这个页面上没有页面加载功能。会话是否有与页面加载的链接C# 会话变量生成错误,c#,asp.net,.net,session,.net-2.0,C#,Asp.net,.net,Session,.net 2.0,我正在尝试使用会话,但出现错误: 当前上下文中不存在名称“会话” 我做错了什么,我使用的是n层,在这个页面上没有页面加载功能。会话是否有与页面加载的链接 public bool CheckDate(ArrayList roles, string username, string password, string locat) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["S
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();
}
}
如果您的方法不在继承自
页面
的类中,则不会继承会话
属性
使用HttpContext
类的Current
属性访问会话
集合所在的当前http上下文:
HttpContext.Current.Session["days"] = day;
如果您的方法不在继承自
页面
的类中,则不会继承会话
属性
使用HttpContext
类的Current
属性访问会话
集合所在的当前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
{
}
并关闭数据读取器。更好地将所有内容包装在使用块中:
无论如何,您可以使用以下技巧缩短代码:
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
{
}
并关闭数据读取器。更好地将所有内容包装在使用块中:
非常感谢你@Guffa。现在我们可以把它当作简单的会话变量吗?@RaniaUmair:它与您使用
页面
类中的会话
属性访问的集合相同。这只是http上下文对象中集合的快捷方式。非常感谢@Guffa。现在我们可以把它当作简单的会话变量吗?@RaniaUmair:它与您使用页面
类中的会话
属性访问的集合相同。它只是http上下文对象中集合的快捷方式。