cookie 保存登录状态


用C#如何创建、读取cookie:
 
一、创建cookie,并写入数据:
 
   //创建、写入Cookie
 
    HttpCookie cookie = Request.Cookies["MWS_User"];
 
    if (cookie == null)
 
    {
 
          cookie = new HttpCookie("MWS_User");
 
    }
 
    cookie.Values.Set("UserID", strUserID);
 
    Response.SetCookie(cookie);

 
 
二、读取cookie:
 
HttpCookie cookie = Request.Cookies["MWS_User"];
 
if (cookie != null && cookie["UserID"].ToString() != "")
 
{
 
      Response.Write("cookie=" + cookie["UserID"].ToString());
 
 }


例子: 登录页面保存:记住登录状态:保存用户名密码:

 
 1 获取cookie

          Page_Load(object sender, EventArgs e)
       
            HttpCookie admincookie =Request.Cookies["userAdmin"];
            
            if (admincookie!=null && admincookie["username"].ToString() != "")
            {
                this.username.Value = admincookie["username"].ToString();
                 this.userpass.Attributes.Add("value", admincookie["userpass"].ToString());
             }
        }

        //登录
  2  创建cookie

      protected void login_submit_btn_Click(object sender, EventArgs e)
        {
            Maticsoft.BLL.users adminbll = new Maticsoft.BLL.users();
            string adminname = username.Value.Trim();
            string adminpass = userpass.Text.Trim();
            if (Session["Code"] != null && TxtYanZheng.Text.Trim() == Session["Code"].ToString())
            {
                string whereStr = "name = '" + adminname + "' and password = '" + adminpass + "'";
                Maticsoft.Model.users  admin = adminbll.GetList(whereStr).Tables[0].Rows.Count != 0 ? adminbll.GetModel(int.Parse(adminbll.GetList(whereStr).Tables[0].Rows[0][0].ToString())) : null;
                if (admin != null)
                {
                    if (admin.sign.Trim().Equals("admin"))
                    {
                        if (this.CheckBox1.Checked)
                        {
                            HttpCookie admincookie = Request.Cookies["userAdmin"];
                            if (admincookie == null)
                            {
                                admincookie = new HttpCookie("userAdmin");
                            }
                            admincookie.Values.Set("username", adminname);
                            admincookie.Values.Set("userpass", adminpass);
                            admincookie.Expires = System.DateTime.Now.AddMinutes(20);
                            Response.SetCookie(admincookie);
                        }
                        if (new Maticsoft.BLL.users().Update(admin))
                        {
                            Session["admin"] = admin;
                            Response.Redirect("~/Admin/main.aspx");
                        }
                    }
}
}
}

 

 

 

移除cookie的 某个值

 

 usersign.Values.Remove(“name”);

你可能感兴趣的:(c#,开发)