程序中保存状态的方式之 Cookies,之前写过一篇关于的。现在继续总结Cookies方式的
新建的测试页面login
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
后台.cs文件
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;public partial class Login : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { } protected void btn_login_Click(object sender, EventArgs e) { string name = txtName.Text.Trim(); string pwd = txtPwd.Text.Trim(); if (name == string.Empty) { MessageBox.Show(this, "请输入用户名!"); return; } if (pwd == string.Empty) { MessageBox.Show(this, "请输入密码!"); return; } if (name == "test" && pwd == "123456") { Response.Cookies.Add(new HttpCookie("comID", "100")); Response.Cookies["comID"].Expires = DateTime.Now.AddDays(30);//设置过期时间,30天 Response.Redirect("获取cookies.aspx"); } else { MessageBox.Show(this,"用户名密码错误!"); } } }
获取cookies.aspx页面后台
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;public partial class 获取cookies : System.Web.UI.Page{ public string comid = ""; protected void Page_Load(object sender, EventArgs e) { if (Request.Cookies["comID"] != null && Request.Cookies["comID"].Value != "") { comid = Request.Cookies["comID"].Value;//获取存入的comid } MessageBox.Show(this, "登录id=" + comid); }}
删除Cookies
Response.Cookies[CountAdmin].Expires = DateTime.Now.AddDays(-1);//删除cookie
我登录的时候存入了100,访问login.aspx就会跳转到获取cookies页面,提示登录id=100,效果图如下: