asp教程.net cookie记录用户登录次数与防止同一账户重复登录
放在登陆成功的地方:
string key = textbox1.text; //用户名文本框设为cache关键字
string uer = convert.tostring(cache[key]); //读取cache中用户相应的值
if (uer == null || uer == string.empty)//判断cache中是否有用户的信息,如果没有相关的值,说明用户未登陆
{
//定义cache过期时间
timespan sesstimeout = new timespan(0, 0, system.web.httpcontext.current.session.timeout, 0, 0);
//第一次登陆的时候插入一个用户相关的cache值,
httpcontext.current.cache.insert(key, key, null, datetime.maxvalue, sesstimeout, system.web.caching.cacheitempriority.notremovable, null);
session["adminid"] = textbox1.text;
response.redirect("main.aspx");
}
else
{
//重复登陆 response.write("<script>alert('您的账号已经登陆!');window.location='login.aspx';</script>");
}
次数加1
if (request.cookies["logincount"] == null)
{
httpcookie c= new httpcookie("logincount"); ;
response.cookies["logincount"].value = "1";
response.cookies["logincount"].expires = datetime.now.adddays(1);
response.cookies.add(c);
}
else
{
int count = convert.toint32(request.cookies["logincount"].value) + 1;
response.cookies["logincount"].value = count.tostring();
}
if (request.cookies["usercookie"] == null)
{
httpcookie usercookie = new httpcookie("usercookie");
usercookie.values["username"] = userinfo.username.tostring();
usercookie.values["lastvist"] = datetime.now.tostring();
usercookie.values["count"] = "1";
usercookie.expires = datetime.now.adddays(30);
response.cookies.add(usercookie);
}
else
{
int counter = convert.toint32(request.cookies["usercookie"]["count"]) + 1;
httpcookie usercookie = new httpcookie("usercookie");
usercookie.values["username"] = userinfo.username.tostring();
usercookie.values["lastvist"] = datetime.now.tostring();
usercookie.values["count"] = counter.tostring();
usercookie.expires = datetime.now.adddays(30);
response.cookies.add(usercookie);
}在另一个页面取出来
//读取cookie
string namecookie = request.cookies["usercookie"]["username"];
response.write("用户名:" + namecookie);
string timecookie = request.cookies["usercookie"]["lastvist"];
response.write(" <br>上传访问时间:" + timecookie);
string countcookie = request.cookies["usercookie"]["count"];
response.write(" <br>访问次数:" + countcookie);