简单的Cookie登录

登录页前台代码

    <form id="form1" action ="" method="post">
        <input type="text" name="txtN" />
        <input type="password" name="txtP" />
        <input type="submit" value="登陆" />
    </form>

 登录页面后台代码

  protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod.ToLower() == "post")
            {
                string strN = Request.Form["txtN"];
                string strP = Request.Form["txtP"];
                //登录成功
                if (strN == "admin" && strP == "123")
                {
                    //创建Cookie  存入  键值对
                    HttpCookie cookie = new HttpCookie("cname", strN);
                    //设置失效时间(硬盘Cookie)
                    cookie.Expires = DateTime.Now.AddMinutes(2);//2分钟内免登陆
                    //加入响应报文对象
                    Response.Cookies.Add(cookie);

                    //让浏览器重定向到首页
                    Response.Redirect("cookieIndex.aspx");
                }
            }
        }

 首页后台代码

 protected void Page_Load(object sender, EventArgs e)
        {
            //获取浏览器端发来的Cookie
            HttpCookie cookie = Request.Cookies["cname"];
            //如果没有则跳转到登录页面
            if (cookie == null)
            {
                Response.Write("<script>alert('您还没有登录~~!');window.location='CookieLogin.aspx';</script>");
                Response.End();
            }
            else
            {
          //如果有则把Cookie里保存的用户名显示出来 Response.Write("欢迎你登录"+cookie.Value); } }

图解:

ok结束

posted @ 2014-04-17 13:54  李小争  阅读(568)  评论(0编辑  收藏  举报