使用session和cookie实现首次登录后,3天之内免登录

 public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected override void OnInit(EventArgs e)
        {
            if (Session["uInfo"] == null)
            {
                //1.判断用户是否勾选记住三天免登陆
                if (Request.Cookies["uid"] != null)
                {
                    var TableAdapter = new WebApplication2.DataSet1TableAdapters.BlogUserTableAdapter();
                    var DataTable = TableAdapter.GetDataByUID(int.Parse(Request.Cookies["uid"].Value));

                    //3.将实体存入session中
                    Session["uInfo"] = DataTable.Rows[0];
                    return;
                }
                //4.跳转到登陆页面
                Response.Redirect("/Login.aspx");
            }
            base.OnInit(e);
        }


    }

 

 public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                     
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var TableAdapter = new WebApplication2.DataSet1TableAdapters.BlogUserTableAdapter();
            var DataTable = TableAdapter.GetDataByName(txtUserName.Text);

            //2.判断用户集合是否存在
            if (DataTable.Rows.Count > 0)
            {
                //3.将用户信息保存到session中
                Context.Session["uInfo"] = DataTable.Rows[0];
                //4.判断用户是否选中了记住登陆
                if (ckbThree.Checked)
                {
                    //5.记住了就将用户id存入cookie中
                    HttpCookie cookie = new HttpCookie("uid", DataTable.Rows[0]["uid"].ToString());
                    cookie.Expires = DateTime.Now.AddDays(3);
                    Context.Response.Cookies.Add(cookie);
                }
                Response.Write("<script>alert('登陆成功');window.location='WebForm1.aspx'</script>");
            }
            else
            {
                Response.Write("<script>alert('登陆失败,请重新登陆');window.location='/Login.aspx'</script>");
            }
            Response.End();  
        }

      


    }

 

 

<form id="form1" runat="server">
        <div>
            登录名:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
            记住三天免登录:<asp:CheckBox ID="ckbThree" runat="server" />
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </div>
    </form>

 

 

转载自https://www.cnblogs.com/ingstyle/p/4081267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值