2008-11-12 127 views
2

我使用Forms Authentication創建了一個自定義登錄頁面,並使用sQL DB來存儲用戶數據。我能夠從用戶名創建一個會話變量,但是想知道是否可以拉出一個單獨的字段並基於此創建一個會話變量。我希望會話變量基於SalesNumber一個5位十進制字段。請給我任何意見或建議。來自SQL DB的Asp.net會話變量

cmd = new SqlCommand("Select pwd,SalesNumber from users where [email protected]", conn); 
cmd.Parameters.Add("@userName", System.Data.SqlDbType.VarChar, 25); 
cmd.Parameters["@userName"].Value = userName; 
Session["userName"] = userName; 

感謝....

回答

1

也請記住,你可以存儲整個對象在會議上,而不是獨立變量:

UserObject user = DAL.GetUserObject(userName); 
Session["CurrentUser"] = user; 
// Later... 
UserObject user = Session["CurrentUser"] as UserObject; 
// ... 

要添加上,你可以在一個妮把它包ce物業:

private UserObject CurrentUser 
{ 
    get 
    { 
      return this.Session["CurrentUser"] as UserObject; 
    } 
    set 
    { 
      this.Session["CurrentUser"] = value; 
    } 
} 
1

當你從你的數據庫查詢SalesNumber,只需使用

Session["SalesNumber"] = <the value of the SalesNumber column from the query> 

還是有別的東西我失蹤的問題... ?

1
在DAL

只需創建一個像你登錄序列:

public bool LoginUser(String username, String password) 
{ 
    bool r = false; 
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString)) 
    { 
     using(SqlCommand cm = new SqlCommand()) 
     { 
      cm.Connection = cn; 
      cm.CommandType = CommandType.Text; 
      cm.CommandText = "SELECT Name, SalesNumber FROM users WHERE uname = @username AND pwd = @password;"; 
      cm.Parameters.AddWithValue("@username", username); 
      cm.Parameters.AddWithValue("@password", password); 

      cn.Open(); 
      SqlDataReader dr = cm.ExecuteReader(); 

      if (dr.HasRows) 
      { 
       // user exists 
       HttpContext.Current.Session["SalesNumber"] = dr["SalesNumber"].ToString(); 
       HttpContext.Current.Session["Username"] = username; 
       HttpContext.Current.Session["Name"] = dr["Name"].ToString(); 

       r = true; 
      } 
      else 
      { 
       // Clear all sessions 
       HttpContext.Current.Session["SalesNumber"] = ""; 
       HttpContext.Current.Session["Username"] = ""; 
       HttpContext.Current.Session["Name"] = ""; 
      } 
     } 
    } 
    return r; 
} 

從您的代碼,在登錄按鈕單擊事件只是增加

if (dalLogin.LoginUser(TextBoxUsername.Text.Trim(), TextBoxPassword.text.Trim())) 
{ 
    // User logged in sucessfuly 
    // all sessions are available 
    Response.Redirect("homepage.aspx"); 
} 
else 
{ 
    // Username and password did not match! show error 
}