2014-01-08 54 views
0

我想在我的login頁面中實現記住我的功能。爲此,我使用了Cookie。它工作正常,但登錄和註銷兩次後,然後嘗試登錄相同的用戶名和密碼後,它顯示無效的用戶名和密碼。爲登錄頁「記住我」的Cookies不起作用

protected void Page_Load(object sender, EventArgs e) 
    { 
     lblStatus.Visible = false; 
     if(Request.Cookies["temp"] != null) 
     { 
      txtUsername.Text = Request.Cookies["temp"].Values["u"]; 
      txtPassword.Text = Request.Cookies["temp"].Values["p"]; 
     } 
    } 
    protected void btnLogn_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection(str); 
     con.Open(); 
     string username = txtUsername.Text; 
     string password = txtPassword.Text; 
     SqlCommand cmd = new SqlCommand("select username from Login where username='"+username+"' AND password='"+password+"'",con); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     if (dr.Read()) 
     { 
      HttpCookie ht = new HttpCookie("temp"); 
      if(CheckBox1.Checked) 
      { 

       ht.Values["u"] = txtUsername.Text; 
       ht.Values["p"] = txtPassword.Text; 
       Response.Cookies.Add(ht); 
       Response.Redirect("Home.aspx"); 
      } 
      else 
      { 
       if (Request.Cookies["temp"] != null) 
       { 
        ht.Values["u"] = ""; 
        ht.Values["p"] = ""; 
        Response.Cookies.Add(ht); 
       } 
       Response.Redirect("Home.aspx"); 
      } 
     } 
     else 
     { 
      lblStatus.Visible = true; 
      lblStatus.Text = "Invalid username or Password"; 
      lblStatus.ForeColor = Color.Red; 

     } 
    } 

產品網頁,我只有一個按鈕的代碼(註銷)

protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
    protected void btnLogout_Click(object sender, EventArgs e) 
    { 

     Response.Redirect("Login.aspx"); 

    } 
+1

有你曾經聽說過SQL注入攻擊? –

+0

沒有。我不知道這個 –

回答

1

檢查回發在你的頁面加載 代碼如下

protected void Page_Load(object sender, EventArgs e) 
    { 
    lblStatus.Visible = false; 
    if(!Page.IsPostBack) 
    { 
      if(Request.Cookies["temp"] != null) 
      { 
       txtUsername.Text = Request.Cookies["temp"].Values["u"]; 
       txtPassword.Text = Request.Cookies["temp"].Values["p"]; 
      } 
    } 
    } 

在你代碼點擊按鈕後,舊的cookie值會替換文本框的當前值

+0

和另外一件事情,當我將文本模式設置爲密碼的密碼,然後cookie不會寫密碼框中的密碼 –

+0

這是在密碼模式下TextBoxes的自然行爲。 – Alborz