“记住我”的Cookie不起作用

时间:2014-01-08 19:01:31

标签: c# asp.net cookies

我想在我的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");

    }

1 个答案:

答案 0 :(得分:1)

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

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