我正在使用 C# 中的以下 SQL 查询 wirrten 从表 ts_dept 中检索 dept 的值 - 当 (CurrentName !=空)
?
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username = Login_Box.UserName;
string pwd = Login_Box.Password;
string strConn;
strConn = WebConfigurationManager.ConnectionStrings["team13ConnectionString"].ConnectionString;
SqlConnection Conn = new SqlConnection(strConn);
Conn.Open();
string sqlUserName;
sqlUserName = "SELECT dept FROM ts_dept WHERE id=@username AND pass=@pwd";
SqlCommand com = new SqlCommand(sqlUserName, Conn);
com.Parameters.Add("@username", username);
com.Parameters.Add("@pwd", pwd);
string CurrentName;
CurrentName = (string)com.ExecuteScalar();
if (CurrentName != null)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
最佳答案
这里只是凭内存(不是在我的 C# 机器上),但试试这个:
object CurrentName = com.ExecuteScalar();
if (CurrentName != null && CurrentName != System.DBNull.Value) {
{
Session["UserAuthentication"] = (string)CurrentName;
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
如果我没记错的话,如果查询没有返回结果,CurrentName 将为 null,如果查询返回结果但 ts_dept.dept 为 null,则 System.DBNull.Value。
还要注意有关使用 session 进行身份验证的评论 - 如果您位于负载平衡的集群中,那么它显然无法工作。开始将其切换为表单例份验证。
关于c# - 将从部门检索到的 SQL 值分配给 session ["UserAuthentication"],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15589955/