c# - 将从部门检索到的 SQL 值分配给 session ["UserAuthentication"]

标签 c# asp.net mysql

我正在使用 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/

相关文章:

c# - 如何安排数据库任务?

c# - dapper:使用 QueryMultiple 同时获取结果和计数

c# - 服务器上的 mysql 版本 6.9.5 出现错误

javascript - 如何在单页应用程序 (SPA) 中实现 ReCaptcha

SQL - 如何用单个 future 日期时间替换一系列日期时间?

MySQL基于组的自增

c# - 寻找具有广泛单元测试的*小型*、开源、c# 项目

c# - C#中字符串到日期时间的转换

c# - C# ConcurrentDictionary InvalidOperationException

MySQL ORDER BY (DESC|ASC) 得到相同的结果