2016-06-14 5 views
0

私はデータベースにユーザー名とパスワードを入力し、挿入されたユーザー名とパスワードに従ってユーザー役割を取得したいが、このコードは仕事データベースから受け取ったユーザーの役割を判断する方法

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 [email protected]_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 

答えて

0

笑、見て、あなたが名前のユーザーテーブルを持っているDBでは、この複雑な

を行う必要は、合格と役割をありません

ので、役割は、私がSqlExecuteScalar

public bool IsAdmin(string u_name, string u_password) 
{ 
string role=""; 
string sql = "select u_role from user_sys 
where [email protected]_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"; 
} 
01とアプリのチェックで を示唆し、管理者またはない

です

は最後にバイバイ

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


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

それを呼び出すと楽しい時を過します!

関連する問題