如果管理员与否,如何确定从数据库接收的用户角色

How to determine the user role that received from database if admin or not

i want to to take the user name and password to the database and get the user role according to the inserted user name and password but this code does not work

 public bool Login(out string Msg)
    {
        bool b = true;
        Msg = "";
        SqlConnection con = new SqlConnection(connection.connectstr);
        try
        {
            con.Open();
            SqlCommand com = new SqlCommand("user_proc", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.Add("@u_name", SqlDbType.NVarChar).Value = this.u_name;
            com.Parameters.Add("@u_password", SqlDbType.NVarChar).Value = this.u_password;
            com.ExecuteNonQuery();

            con.Close();
            b = true;
        }
        catch (Exception ex)
        {
            con.Close();
            Msg = ex.Message;
            b = false;
        }

        return b;
    } 

以及应该将角色检查到数据库中的 C# 代码,如果不是管理员,则将我重定向到服务器页面,如果不是,则重定向到客户端页面:-

protected void btn_login_Click(object sender, EventArgs e)
    {
        my_user u = new my_user();
        u.u_name = TextBox1.Text;
        u.u_password = TextBox2.Text;
        string m="";

        if (!u.Login(out m))
        {
            lbl_role.Text = "error";                
        }
        else
        {
            if (u.u_role == "admin")
            {
                Response.Redirect("testclient.aspx");
            }
            else Response.Redirect("testserver.aspx");

        }
    }

执行该任务的数据库过程是:

create procedure user_proc  
  (@u_name nvarchar(50) , 
  @u_password nvarchar(50), 
  @u_role nvarchar(50))
  as 
  begin
  begin try
  begin transaction  
  if exists (select u_role from user_sys
 where u_name=@u_name and u_password= @u_password)
  commit
End try
Begin catch
rollback
declare @msg varchar(200)
set @msg = ERROR_MESSAGE()
raiserror(@msg , 16 , 1)
End catch
End

呵呵,你看,不用这么复杂

在数据库中,您有一个用户 table,其名称、密码和角色

所以,角色是不是admin

那我建议 在您的应用程序中检查 SqlExecuteScalar

public bool IsAdmin(string u_name, string u_password)
{
string role="";
string sql = "select u_role from user_sys
where u_name=@u_name and u_password= @u_password";

using (SqlConnection conn = new SqlConnection(connection.connectstr))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add(new SqlParameter("@u_name", u_name));
    cmd.Parameters.Add(new SqlParameter("@u_password", u_password));
    try
    {
        conn.Open();
        role = cmd.ExecuteScalar().ToString();
    }
    catch (Exception ex)
    {
        //handle error
    }
}
return role == "admin";
}

终于叫出来了

    string u_name = TextBox1.Text;
    string u_password = TextBox2.Text;


    if (IsAdmin(u_username,u_password))
        //it is admin
    else 
        //it is not admin

再见,玩得开心!