页面重定向

时间:2009-07-14 07:22:46

标签: c# sql sql-server redirect

登录成功后如何从登录页面重定向到主页? 我有一个数据库,它存储用户名和密码。 在登录时,它将通过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 个答案:

答案 0 :(得分: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(“/ relative / path / to / home.page”,false);将您重定向到主页。

我会考虑重构该代码,以便您有一些方法:

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 :(得分:1)

除了Mauro的回答,还有一些您可能想要考虑的其他变化:

  1. 将Web控件重命名为更有意义的名称,例如txtPassword。
  2. 将连接字符串存储在Web.config文件中,这样您就可以更灵活地从测试过渡到生产。
  3. 在连接周围使用using语句而不是try finally。
  4. SqlDataAdapter将处理关闭和打开连接。
  5. 如果您使用的是SQL Server 2005或更高版本,则可以使用参数而不是SP(SP不会比内联SQL有太多的性能提升)。

答案 2 :(得分:0)

你的gridview没有意义,好像登录不成功,它什么都不包含,如果登录成功,你将转到另一页。

相关问题