使用c#中的会话
本文关键字:会话 使用 | 更新日期: 2023-09-27 18:00:55
这是我在C#中使用会话登录的代码。我已经为此编写了业务逻辑和数据访问层,但我的代码并没有按预期工作。即使数据库中没有记录,我也可以登录,它会重定向到error.aspx
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_验证
public class BL_Authenticate
{
public static DataSet AuthenticateUser(DataSet user, string login, string password)
{
return DAL_Authenticate.AuthenticateUser(user, login, password);
}
}
DAL_验证
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;
}
我看到的一件正常的事情是,如果登录失败,它会重定向到一个错误页面,所以没有错误,你确定你的登录在那一点上有效吗?