2009-07-14 169 views
0

登录成功后,我如何从登录页面重定向到主页? 我有一个数据库,它存储用户名和密码。 在登录时它将通过sql查询来检查用户名和密码。 我的代码如下所示。页面重定向

protected void Button1_Click(object sender, EventArgs e) 
    { 
     if (TextBox1.Text == "") 
     { 
      Label3.Visible = true; 
      Label3.Text = "* Required Field"; 
     } 
     else if (TextBox2.Text == "") 
     { 
      Label4.Visible = true; 
      Label4.Text = "* Required Field"; 
     } 

     else 
     { 
      Label3.Visible = false; 
      Label4.Visible = false; 
      userid = TextBox1.Text; 
      pass = TextBox2.Text; 

      SqlConnection conn = new SqlConnection("SERVER= server3\\OFFICESERVERS; Initial catalog = Web; Integrated Security = SSPI"); 
      SqlCommand mycmd = new SqlCommand(); 
      mycmd.Connection = conn; 
      mycmd.CommandText = "SELECT FirstName, LastName, MiddleName, Email, Age FROM web WHERE IsActive=1 AND LoginName='" + userid + "' " + "AND Password='" + pass + "'"; 

      try 
      { 

       conn.Open(); 
       mycmd.ExecuteScalar(); 
       SqlDataAdapter da = new SqlDataAdapter(mycmd); 
       DataTable dt = new DataTable(); 
       da.Fill(dt); 
       GridView1.Visible=true; 
       GridView1.DataSource = dt; 
       GridView1.DataBind(); 
       TextBox1.Text = ""; 
       TextBox2.Text=""; 


      } 

      finally 
      { 
       conn.Close(); 
       conn.Dispose(); 
      } 
     } 
    } 

我的要求是,如果登录成功我甲肝从登录页面重定向到主页,而不是GridView控件绑定。 它是如何完成的?

回答

3

首先,看看使用存储过程!这个SQL命令,让你大开的问题SQL注入(guard against SQL injection

mycmd.CommandText = "SELECT FirstName, LastName, MiddleName, Email, Age FROM web WHERE IsActive=1 AND LoginName='" + userid + "' " + "AND Password='" + pass + "'"; 

如果我进入

' = '' or '1'='1 

我的密码,这将让我在与我想要的任何用户名!

其次,你可以做一个的Response.Redirect( “/相对/路径/到/ home.page”,假);将您重定向到主页。

我想看看重构的代码,所以你有几个方法:

protected bool Login(string username, string password) //handles logging the user in 
protected void LoginSuccess() //handles the redirect if the user successfully logs in. 
protected void BindDatagrid() //handles the databind if the user didn't log in. 
+1

你打败了我。很好的答案。 – BinaryMisfit 2009-07-14 07:49:30

1

除了毛罗的答案在这里,你可能要考虑一些其他的变化:

  1. 将您的Web Controls重命名为更有意义的名称,例如txtPassword。
  2. 将连接字符串存储在Web.config文件中,以便您可以在测试之间进行更灵活的转换。
  3. 最后在连接中使用using语句而不是try。
  4. SqlDataAdapter将处理关闭和打开连接。
  5. 你可以,如果你使用SQL Server 2005或以上,而不使用SP参数(SP将不会有太大的超过内嵌SQL的性能改进)。
0

你的gridview是毫无意义的,就好像登录不成功,它将不包含任何内容,并且如果登录成功,你将移动到另一个页面。