[英]ASP.NET Login in n-tier architecture
我正在嘗試在基於n層體系結構的ASP.NET C#中實現登錄功能。
資料存取:
public int userlogin(string user, string passw)//checking the user name and password
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT NurseName, password FROM Nurse2 WHERE NurseName = '" + user.Trim() + "' AND Password = '" + passw.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
表示層.cs文件
protected void Button1_Click(object sender, EventArgs e)
{
string name = TextBox1.Text;
string password = TextBox2.Text;
int id = da.userlogin(name, password);
if (id > 0)
{
Session["userName"] = name;
Response.Redirect("SubscribePage.aspx");
}
else
{
Label1.Text = "invalid";
}
現在,我的問題是,即使我輸入正確的數據,當我按下按鈕時,程序也會簡單地轉到else子句。 在我看來,這里可能不行的事情似乎還不錯。
我認為您現在不需要這樣做。 ASP.NET具有內置身份驗證。 只需檢查一下https://msdn.microsoft.com/en-us/library/xdt4thhy(v=vs.140).aspx 。
N-Tier體系結構有助於分離您的代碼,因為您的代碼正在跳過一層並且沒有充分利用業務邏輯層。 這是一個有用的圖像;
我還將添加一個額外的類來存儲您的用戶登錄詳細信息,我想您將擁有更多信息以及要存儲的護士姓名-您可以將此類的實例存儲在會話數據中,並在需要時將其丟棄;
public class User
{
public string Name { get; set; }
/* Some other attributes - not your password though! */
}
-
介紹;
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Session["User"] = BLL.userLogin(TextBox1.Text, TextBox2.Text);
Response.Redirect("SubscribePage.aspx"); /* If it reaches here, everything is okay */
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
業務層;
public static User userLogin(string username, string password)
{
User U = DAL.userLogin(username, password);
if (string.IsNullOrEmpty(U.Name))
throw new Exception("Incorrect login details");
return U;
}
數據訪問層;
public static User userLogin(string username, string password)
{
using (SqlConnection con = new SqlConnection(GetConnectionString())
{
User U = new User();
SqlCommand cmd = new SqlCommand(@"SELECT NurseName, password
FROM Nurse2
WHERE NurseName = @user AND password = @pw", con);
cmd.Parameters.Add(new SqlParameter("@user", username));
cmd.Parameters.Add(new SqlParameter("@pw", password));
try
{
con.Open();
}
catch (Exception ex)
{
throw new Exception("connetion problem", ex);
}
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
U = rdr["NurseName"];
}
}
}
catch (Exception ex)
{
throw new Exception("problem with query", ex);
}
finally
{
con.Close(); /* Clean up regardless of the outcome */
con.Dispose();
}
return U;
}
}
閱讀有關N-Tier體系結構的更多信息,並嘗試try-catch語句。 希望能幫助到你。 我還將改進控件的命名約定,以使生活更輕松(即Label1-> lblError)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.