0
這是我在C#中使用會話進行登錄的代碼。我爲此編寫了業務邏輯和數據訪問層,但我的代碼沒有按預期工作。即使在DB沒有記錄,我能夠登錄並重定向到error.aspx
在c#中使用會話#
Default.aspx.cs
public void LoginButton_Click(object sender, System.EventArgs e)
{
int id;
if (LoginName.Text!=""&& Password.Text!="")
{
try
{
sessionVars = BL_Authenticate.AuthenticateUser(sessionVars, LoginName.Text, Password.Text);
Response.Redirect("home.aspx");
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
//else
//{
// Response.Redirect("error.aspx");
//}
if (sessionVars.Tables[0].Rows.Count >= 1)
{
try
{
Session["User"] = (string)sessionVars.Tables[0].Rows[0]["FirstName"];
Session["User"] += (string)" ";
Session["User"] += (string)sessionVars.Tables[0].Rows[0]["LastName"];
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
id = (int)sessionVars.Tables[0].Rows[0][0];
if (id >= 1)
{
try
{
Session["Role"] = "Admin";
FormsAuthentication.Authenticate((string)sessionVars.Tables[0].Rows[0]["Login"], (string)sessionVars.Tables[0].Rows[0]["Password"]);
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
if (FormsAuthentication.GetRedirectUrl("Admin", false) == "/UserInterface/home.aspx")
{
FormsAuthentication.RedirectFromLoginPage("admin", false);
Response.Redirect("home.aspx");
}
else
FormsAuthentication.RedirectFromLoginPage("admin", false);
}
else
{
Session["Role"] = "User";
FormsAuthentication.RedirectFromLoginPage("user", false);
}
}
else
{
errorMessage.Text = "Sorry, wrong username or password.";
}
}
}
}
BL_Authenticate
public class BL_Authenticate
{
public static DataSet AuthenticateUser(DataSet user, string login, string password)
{
return DAL_Authenticate.AuthenticateUser(user, login, password);
}
}
DAL_Authenticate
public static DataSet AuthenticateUser(DataSet dataset, string login, string password)
{
try
{
//Dispose all objects that have a .Dispose()
SqlDataAdapter adapter = new SqlDataAdapter();
conn = DAL_DataBaseConnection.GetConnection();
SqlCommand cmd = new SqlCommand("authentication", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("@Login", SqlDbType.VarChar, 255);
param.Value = login;
param = cmd.Parameters.Add("@Password", SqlDbType.VarChar, 255);
param.Value = password;
adapter.SelectCommand = cmd;
adapter.Fill(dataset);
}
finally
{
conn.Close();
}
return dataset;
}
請至少郵編將編譯的代碼。在那裏有一個'catch'塊,沒有匹配的'try'。 – DavidG
@DavidG對不起:當我修改我的代碼時錯過了 –
@DavidG你能幫我現在幫我 –