首页 > 学院 > 开发设计 > 正文

ASP.NET中Cookie的使用

2019-11-17 04:07:38
字体:
来源:转载
供稿:网友
设计意图:将login页面中的登录信息保存在login的Cookie中,转到Home页面时,利用得到的Cookie值就能自动登录

login页面前台关于Cookie的代码:

<td>
      &nbsp;&nbsp;&nbsp;&nbsp;
        <asp:DropDownList ID="time" runat="server">
           <asp:ListItem Selected="True" Value="1">不保存</asp:ListItem>
           <asp:ListItem Value="14">两周</asp:ListItem>
           <asp:ListItem Value="30">一个月</asp:ListItem>
           <asp:ListItem Value="0">不创建</asp:ListItem>
        </asp:DropDownList>

</td>

login页面后台关于Cookie的代码:

PRotected void Login_Click(object sender, EventArgs e)
    {

        //创建一个新的Cookie
        HttpCookie newCookie = new HttpCookie("User");

        //往Cookie里面添加值,均为键/值对。Cookie可以根据关键字寻找到相应的值
        newCookie.Values.Add("Name",nameID.Text.Trim());
        newCookie.Values.Add("Pwd",pwdID.Text.Trim());
        

       //设置session的值

        Session["Name"] = nameID.Text.Trim();
        Session["Pwd"] = pwdID.Text.Trim();

        if (time.SelectedValue == "14")
        {
            newCookie.Expires = DateTime.Now.AddDays(14);
        }
        else if (time.SelectedValue == "30")
        {
            newCookie.Expires = DateTime.Now.AddDays(30);
        }
        else if (time.SelectedValue == "0")
        {
            newCookie.Expires = DateTime.Now.AddDays(0);
        }

        //Cookie的设置页面要用Response
        Response.AppendCookie(newCookie);
        Response.Redirect("Home.aspx");
    }

    //Home页面前台代码

   <asp:Button ID="btnReset" runat="server" Text="注销" onclick="btnReset_Click"
            Visible="False" />

//Home页面后台代码

protected void Page_Load(object sender, EventArgs e)
    {

        //获得login页面的Cookie值 要用Request
        HttpCookie newCookie = Request.Cookies["User"];
        if (newCookie != null)
        {
            Response.Write("欢迎" + newCookie.Values["Name"] + "来到该网站," + "你的密码是:" + newCookie.Values["Pwd"]);
            btnReset.Visible = true;
        }

        //获得login页面的session值
         if (Session["Name"] != null)
        {
            Response.Write("欢迎" + Session["Name"] + "来到该网站," + "你的密码是:" + Session["Pwd"]);
            btnReset.Visible = true;
        }
        else
        {
            Response.Write("您还没有登陆!<a href='Login.aspx'>返回登陆</a>");
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        HttpCookie newCookie = Request.Cookies["User"];
        if (newCookie != null)
        {
            newCookie.Expires = DateTime.Now.AddDays(-1);

            Response.Cookies.Add(newCookie);
            Response.Redirect("Login.aspx");
        }
    }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表