Cache对象主要用于Web应用程序的缓存。对于每个应用程序都需要创建Cache对象的一个实例,并且只要对应的应用程序域保持活动,该实例便保持有效,有关Cache对象实例的所有信息都须通过HttpContext对象的Cache属性或Page对象的Cache属性来提供。
本实例中,把用户的登录信息保存在Cache对象中,并设置过期时间为Session变量失效的时间,因此,一旦Session变量失效,Cache对象也就过期了;但Cache对象对所有的用户还可以访问,因此,用它保存用户信息比数据库来得方便。
protected void btnLogin_Click(object sender, EventArgs e)
{
int i = this.checkLogin(txtName.Text,txtPwd.Text);
if (i> 0)
{
string str_Key = txtName.Text + "_" + txtPwd.Text;
// 得到Cache中的给定str_Key的值
string str_User = Convert.ToString(Cache[str_Key]);
// Cache中如果没有str_Key的项目,那么用户没有登录
if (str_User == String.Empty)
{
// TimeSpan构造函数,用来判断是否登录。
TimeSpan SessTimeOut = new TimeSpan(0,0,HttpContext.Current.Session.Timeout,0,0);
HttpContext.Current.Cache.Insert(str_Key,str_Key,null,DateTime.MaxValue,SessTimeOut, CacheItemPriority.NotRemovable,null);
Session["User"] = str_Key;
// 首次登录成功
Response.Write("<h2 style='color:red'>你好,登录成功!");
}
else
{
// 在 Cache 中存在该用户的记录,表名已经登录过,禁止再次登录
Response.Write("<h2 style='color:red'>抱歉,您好像已经登录了!");
return;
}
}
else
{
Response.Write("用户名称或密码错误!!!");
}
}