我已经为登录检查和用户类型检查编写了C#代码。逻辑似乎是正确的,但为什么输出不正确?
我已经为登录检查和用户类型检查编写了C#代码。逻辑似乎是正确的,但为什么输出不正确 我在这里做了一些编辑。 请现在检查这个 没有发生重定向 没有发生重定向 没有发生重定向我已经为登录检查和用户类型检查编写了C#代码。逻辑似乎是正确的,但为什么输出不正确?,c#,asp.net,C#,Asp.net,我已经为登录检查和用户类型检查编写了C#代码。逻辑似乎是正确的,但为什么输出不正确 我在这里做了一些编辑。 请现在检查这个 没有发生重定向 没有发生重定向 没有发生重定向 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuratio
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace Bidders_Joint
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["BiddersJoint"].ToString();
string type;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select Type from TABLE_USER where User_ID = @userid AND Password=@password", con);
cmd.Parameters.AddWithValue("@userid", txtUserid.Text.ToString());
cmd.Parameters.AddWithValue("@password", txtPassword.Text.ToString());
try
{
con.Open();//cmd.Connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
type = dr["Type"].ToString();
if (type == "admin")
{
Response.Redirect("administrator.aspx");
Response.End();
}
else if (type == "general")
{
Response.Redirect("userspage.aspx");
Response.End();
}
}
else
{
lblMessage.Text = "wrong userid or password";
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
finally
{
con.Close(); //cmd.Connection.Close();
}
}
}
}
将第一个和第二个
if
s连接到else
:
while (dr.Read())
{
password = dr["Password"].ToString();
type = dr["Type"].ToString();
if ((password == txtPassword.Text.ToString()) && (type == "admin"))
{
Response.Redirect("administrator.aspx");
}
else if ((password==txtPassword.Text.ToString()) && (type=="general"))
{
Response.Redirect("userspage.aspx");
}
}
lblMessage.Text = "wrong userid or password";
更新:
while (dr.Read())
{
type = dr["Type"].ToString();
if (type == "admin")
{
Response.Redirect("administrator.aspx");
Response.End();
}
else if (type == "general")
{
Response.Redirect("userspage.aspx");
Response.End();
}
}
lblMessage.Text = "wrong userid or password";
每次重定向后都要使用Response.End(),这样可以确保重定向后的代码不会被执行,这在少数情况下可能是有害的。它们在我的代码中没有连接吗?我想我的ifs块也和你在这里显示的一样。@SumitGupta-这是
响应的默认行为。用一个参数重定向。请告诉我为什么我总是得到错误的用户ID或密码。:(@anshulpui-查看我的更新。你需要在心理上(或书面上)练习执行你自己的代码。请散列你的密码。Igor说什么。还有一些其他的事情你可能会想拥有“更干净”的代码。最重要的是,你好像在用纯文本存储数据库中的密码。这很糟糕!请阅读“哈希”和“腌制”。密码。这里有很多。然后你将密码存储在一个变量中,这个变量对整个类都是可见的。这应该是不必要的。将它声明为尽可能靠近使用它的位置。在这种情况下,就在while
之前。说到这里,为什么要使用while
呢?你希望得到>1个结果吗?只需使用if(dr.Read())
。如果dr.Read()
失败了该怎么办?另外,你混合了两件事,检查密码和类型。首先检查(仅)密码。如果密码不匹配,请写“错误的用户ID…”消息并返回。在您知道密码必须匹配后,打开类型
,以知道要重定向到哪个站点。我不知道您的数据库结构,但我注意到您是根据“UserID”查找用户的,大多数开发人员使用自动递增数字id,而不是“username”检查您的数据库,如果您有不同的用户名字段?