简体   繁体   中英

Cookies for “Remember me” are not working

i want to implement the functionality of remember me in my login page.for this purpose i have used cookies. it is working fine but when login and logout twice , then after try to login for the same username and password, it shows invalid username and password. code for login page

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;

        }
    }

code for home page where i have only a single button(Logout)

protected void Page_Load(object sender, EventArgs e)
    {

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

      Response.Redirect("Login.aspx");

    }

Check PostBack in your page load as follows

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"];
            }
    }
    }

In your code after you click the button the old cookie values replace the current values of your textboxes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM