使用文本框和AD身份验证的SQL身份验证

本文关键字:身份验证 SQL AD 文本 | 更新日期: 2023-09-27 18:24:58

嗨,我正在运行两种形式的身份验证。我运行的第一个身份验证是AD身份验证,它运行良好。第二种方法是确认用户名是否在SQL数据库中。我使用此代码来验证SQL中是否存在用户名。

我得到错误

运算符"=="不能应用于类型为"string"answers"System.Data.SqlClient.SqlDataReader"的操作数

使用此代码。。。。

    using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
    {
        SqlCommand cmd = new SqlCommand("select Username from dbo.users", con);
        con.Open();
        SqlDataReader sqlresult = cmd.ExecuteReader();

        if (txtLoginID.Text == sqlresult)
        {
            Response.Redirect("account/orders.aspx");// Authenticated user redirects to default.aspx
        }
        else
        {
            Response.Redirect("default.aspx");// Authenticated user redirects to default.aspx
        }
        con.Close();
    }
}

使用文本框和AD身份验证的SQL身份验证

这里有几个问题。首先查询:

select Username from dbo.users

正在提取表中的所有记录。这不是检查用户名是否存在的正确方法。你需要这样的东西:

select Username from dbo.users WHERE UserName = @UserName

其中,@UserName是包含来自txtLoginID.Text的值的参数。一旦你做到了这一点,你可以使用:

    if(sqlresult.HasRows)
    {
        Response.Redirect("account/orders.aspx");// Authenticated user redirects to default.aspx
    }
    else
    {
        Response.Redirect("default.aspx");// Authenticated user redirects to default.aspx
    }

您还应该查看using语句。

虽然使用上述解决方案并不重要,但出现错误的原因是不言自明的。您正试图将字符串值与SqlDataReader对象进行比较。这是不可能的。