C# 登录 存Session ,cookie并且验证只能一个人登录以及清session并且Cache

string id = ConvertHelper.GetString(ds.Tables[0].Rows[0]["Uid"]);//用户ID
string struserid = string.Empty;//声明一个空字符串
struserid = ConvertHelper.GetString(Cache[id]);//把Cache赋给了struserid
if (struserid == string.Empty)//用if判断struserid是否为空 如果为空的话证明还没有用户登录
{
TimeSpan sessout = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
Cache.Insert(id, id, null, DateTime.MaxValue, sessout, CacheItemPriority.NotRemovable, null);//设置Cache过期时间

Session["Uid"] = ds.Tables[0].Rows[0]["Uid"];//向Session中存一个用户ID
HttpCookie cooke = new HttpCookie("cookie");//创建一个名为cookie的 Cookie对象
cooke.Value = "'" + ds.Tables[0].Rows[0]["Uemail"] + "','" + ds.Tables[0].Rows[0]["Ulogpwd"] + "'";//向cookie的value中存该用户的账号和密码,用于记住密码功能
cooke.Expires = System.DateTime.Now.AddDays(10);//设置Cookie的过期时间
Response.AppendCookie(cooke);//把创建的这个cookie 添加到内部Cookie的集合中
ScriptHelper.ShowAlertAndRedirectScript(this.Page, "登录成功", "/Person/Index.aspx");
}
else
{
ScriptHelper.ShowAlertScript(this.Page,"该用户已登录");
}

下面是当用户点击退出时清除数据(这里需说明不包括异常情况 如:关闭页面,关闭浏览器。就是说必须点退出和等Session过期,你才能登录。别的你们自己找吧)

HttpCookie cooke = new HttpCookie("cookie");//找见你所创的那个Cookie
cooke.Expires = System.DateTime.Now.AddDays(-10);//让它的过期时间变成负数
Response.AppendCookie(cooke);
Session.Remove("Uid");//找见Session名为Uid的把它删除
Cache.Remove("");//把Cache删除

上一篇:mysql 存储过程 demo


下一篇:常用yum命令