繁体   English   中英

“记住我”的Cookie无效

[英]Cookies for “Remember me” are not working

我想在我的login页面中实现记住我的功能。为此,我使用了cookie。 它工作正常,但登录和注销两次后,然后尝试使用相同的用户名和密码登录后,显示无效的用户名和密码。 登录页面代码

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");

    }

检查页面加载中的回发,如下所示

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值替换了文本框的当前值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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