假设我在http://localhost:7924/default上,并输入登录信息,以下是每种情况下的情况:
如果密码错误(或正确)+ login_name不存在=> 刷新页面
如果密码错误+ login_name存在(正确)=>即将 的 error_page
- 醇>
如果两者都正确=>重定向到 CP.aspx
string text = username_login.Text;
string str2 = password_login.Text;
SqlConnection sqlcon = new SqlConnection(Functions.Auth());
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandText = "SELECT TOP 1 password FROM dbo.Accounts WHERE login_name = @login_name";
sqlcmd.Parameters.Add("@login_name", System.Data.SqlDbType.NVarChar).Value = text;
sqlcmd.CommandType = System.Data.CommandType.Text;
sqlcmd.Connection = sqlcon;
sqlcon.Open();
SqlDataReader sqlreader = sqlcmd.ExecuteReader();
string returnString = String.Empty;
while (sqlreader.Read())
{
if (sqlreader["password"].ToString() == Functions.CreateMD5Hash("5487" + str2.ToString()))
{
this.Session["logged_in"] = "true";
this.Session["username"] = text;
base.Response.Redirect("/CP.aspx");
}
else
{
base.Response.Redirect("/error_page?err=login-fail");
}
}
2 & 3。正在工作,但是,第一个不是。我不明白为什么它只刷新页面而不是进入错误页面,因为细节是错误的。 (因为它无法进行比较)
编辑:我还检查了密码是否为NULL =>重定向到error_page但也会刷新页面。
答案 0 :(得分:4)
您只需检查它是否有任何价值。
if(sqlreader.HasRows)
{
While...
}
else
{
//refresh page code here
}
此外,您可能想要考虑更好的架构师n-tie,表示层,业务层,数据访问层。
答案 1 :(得分:1)
从技术上讲:1。如果sqlreader
没有任何行,或者2.如果while loop
中没有任何条件获得true
,则会呈现相同的页面。但是为了获得对页面的引用,您可以使用Response.Redirect(Request.RawUrl)
。我喜欢在代码中做一些更改 - 只是一点点:
// since you are selecting 1 top row, here you would 0 or 1 row at all.
// so you don't need to use `while` and `if` doing well
// also, you won't need to check if `sqlreader.HasRows`,
// because the `if (sqlreader.Read())` does the same.
if (sqlreader.Read())
{
if (sqlreader["password"].ToString() == Functions.CreateMD5Hash("5487" + str2.ToString()))
{
this.Session["logged_in"] = "true";
this.Session["username"] = text;
base.Response.Redirect("/CP.aspx");
}
else
{
base.Response.Redirect("/error_page?err=login-fail");
}
}
// there is no need to use an `else`. just do the redirect:
Response.Redirect(Request.RawUrl);
答案 2 :(得分:0)
尝试在链接前使用~
:
base.Response.Redirect("~/CP.aspx");
答案 3 :(得分:0)
我修改了您的代码并检查它是否可以解决您的问题
public static string ReplaceAll(String Str)
{
Str = Str.Replace("'", " ");
Str = Str.Replace(";", " ");
Str = Str.TrimStart();
Str = Str.TrimEnd();
return Str;
}
public void MyFunction()
{
SqlConnection sqlcon = new SqlConnection(Functions.Auth());
SqlDataAdapter sda = new SqlDataAdapter("SELECT TOP 1 password FROM dbo.Accounts WHERE login_name = '" + ReplaceAll(username_login.Text) + "' and password='" + ReplaceAll(password_login.Text) + "'", sqlcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
this.Session["logged_in"] = "true";
this.Session["username"] = text;
base.Response.Redirect("/CP.aspx");
}
else
{
base.Response.Redirect("/error_page?err=login-fail");
}}