日期:2014-05-18  浏览次数:20735 次

关于web页面登陆的方法
我的登陆方式是下面的代码,但是我这几天看到可以用cookie,还可以用session,我就是来请教一下,如果用cookie怎么改写我的代码呢?要是用session怎么改写啊?
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
  {
  try
  {
  string connstr = "Data Source=.;Initial Catalog=admin;Integrated Security=True";
  SqlConnection conn = new SqlConnection(connstr);
  conn.Open();
  SqlCommand cmd = new SqlCommand("select * from \"Table_admin\" where ID = '" + this.username.Text.Trim() + "' and password = '" + this.password.Text.Trim() + "'", conn);
  SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  if (dr.Read())
  {
  this.Response.Redirect("main.html", true);
  }
  else
  {
  ClientScript.RegisterStartupScript(this.GetType(), "message", "<script language='javascript' >alert('您填写的信息有误');</script>");
  this.username.Text = "";
  this.password.Text = "";
  }
  conn.Close();
  }
  catch (Exception ex)
  {
  this.Response.Write(ex.Message);
  }


------解决方案--------------------
if (dr.Read())
{
Session["userName"]=dr["ID"].ToString();
this.Response.Redirect("main.html", true);
}
以后判断用户是否已登录用
if(Session["userName"]!=null)
//已登录
------解决方案--------------------
Session和Cookie都用:
if (dr.Read())
{
Session["userName"]=dr["ID"].ToString();
Response.Cookies["UserInfo"].Value = dr["ID"].ToString();
Response.Cookies["UserInfo"].Expires = DateTime.Now.AddDays(14); //设定Cookies十四天后过期
this.Response.Redirect("main.html", true);
}