2012-01-11 156 views
0

我將嘗試使用會話,但我得到的錯誤: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(); 
    } 
} 

回答

2

如果你的方法是不是從Page繼承的類時,Session財產不繼承。

使用HttpContext類的Current財產,其中Session收集訪問當前HTTP上下文:

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

非常感謝你@Guffa。現在我們可以把它當作簡單的Session變量嗎? – 2012-01-11 08:24:50

+0

@RaniaUmair:這與使用'Page'類中的'Session'屬性訪問的集合相同。它只是http上下文對象中的集合的一個捷徑。 – Guffa 2012-01-11 08:46:16

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