我已經編寫了用於登錄檢查和用戶類型檢查的C#代碼。邏輯似乎是正確的,但爲什麼輸出不正確?我已經編寫了用於登錄檢查和用戶類型檢查的C#代碼。邏輯似乎是正確的,但爲什麼輸出不正確?
我在這裏做了一些修改。 請現在檢查。
沒有重定向正在發生 沒有重定向正在發生 沒有重定向正在發生
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 [email protected]", 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();
}
}
}
}
請哈希您的密碼。 – zimdanen
@Igor說了什麼。還有其他一些你可能想要考慮的「更乾淨」的代碼。首先,最重要的是,您似乎將密碼以純文本形式存儲在數據庫中。這很糟糕!請閱讀「散列」和「醃製」密碼。在這裏有很多。然後,您將密碼存儲在變量中,這對整個班級都是可見的。這不應該是必要的。儘可能將其聲明到與您一起工作的地方。在這種情況下,就在'while'之前。說到這一點,爲什麼要用'while'?你期望> 1結果?只需使用'if(dr.Read())'。 – Corak
如果'dr.Read()'失敗會發生什麼?此外,你正在混合兩件事,檢查密碼和類型。首先檢查(僅)密碼。如果不匹配,請寫下「錯誤的userid ...」消息並返回。並且在知道密碼必須匹配後,請在'type'上開關以知道要重定向到哪個站點。 – Corak