来自SQL DB的Asp.net会话变量

时间:2008-11-12 21:53:56

标签: c# asp.net

我使用表单身份验证创建了一个自定义登录页面,并使用sQL DB存储用户数据。我能够从用户名创建一个会话变量,但想知道是否可以拉出一个单独的字段并根据它创建一个会话变量。我希望会话变量基于SalesNumber一个5位十进制字段。请给我任何意见或建议。

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

...谢谢

3 个答案:

答案 0 :(得分:1)

从数据库查询中获取SalesNumber时,只需使用

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

或者在问题中我还缺少其他东西......?

答案 1 :(得分: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
}

答案 2 :(得分:1)

另请注意,您可以在会话中存储整个对象,而不是单独的变量:

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

要添加,您可以将其包装在一个不错的属性中:

private UserObject CurrentUser
{
     get
     {
          return this.Session["CurrentUser"] as UserObject;
     }
     set
     {
          this.Session["CurrentUser"] = value;
     }
}
相关问题