网站状态保存方法
采用cookie+session 双重使用,自己写的贴出来,大家指导一下,以下是代码:
public class UserBasePage : System.Web.UI.Page
{
private bool islogin = false;
private string cookieKey = "www";
private PF.Model.UserInfo userinfo = new PF.Model.UserInfo();
//是否登录
public bool IsLogin { get { return islogin; } }
public PF.Model.UserInfo UserInfo { get { return userinfo; } }
protected override void OnInit(EventArgs e)
{
try
{
CheckLogin();
}
catch { }
base.OnInit(e);
}
/// <summary>
/// 检查登录
/// </summary>
public void CheckLogin()
{
long userid = 0;
string username = string.Empty, password = string.Empty;
int isType = 0;
if (Session["UserID"] != null && Session["UserName"] != null && Session["Password"] != null)
{
//Session 获取用户ID
long.TryParse(Session["UserID"].ToString(), out userid);
username = Session["UserName"].ToString();
password = Session["Password"].ToString();
isType = 1;
}
else
{
HttpCookieCollection cookieColl = HttpContext.Current.Request.Cookies;
int count = cookieColl.AllKeys.Length;
HttpCookie mycookie = null;
for (int i = 0; i < count; i++)
{
if (cookieKey.Equals(cookieColl[i].Name))
{
if (mycookie == null || mycookie.Value.Length < cookieColl[i].Value.Length)
{
mycookie = (HttpCookie)cookieColl[i];
}
}
}
//Cookies获取用户ID
if (mycookie != null)
{
long.TryParse(mycookie["UserID"], out userid);
username = mycookie["UserName"].ToString();
password = mycookie["Password"].ToString();
isType = 2;
}
}
if (isType == 0)
{
return;
}
//检查数据库
PF.BLL.UserInfo bll = new UserInfo();
userinfo = bll.GetModel(userid,username, password);
if (userinfo == null)
{
return;
}
else
{
islogin = true;
}
SetFormLogin(userinfo.UserID, userinfo.UserName, password);
}
/// <summary>
/// 设置登录后的验证信息
/// </summary>
public void SetFormLogin(long userid, string username, string password)
{
Session["UserID"] = userid;
Session["UserName"] = username;
Session["Password"] = password;//未加密的密码
Session.Timeout = 600;
HttpCookie cookie = new HttpCookie(cookieKey);
cookie["UserID"] = userid.ToString();
cookie["UserName"] = username;
cookie["Password"] = password;//未加密码的密码
cookie.Expires = DateTime.MaxValue;
try
{
HttpContext.Current.Response.Cookies.Add(cookie);
}
catch
{
Response.Cookies.Add(cookie);
}
}
/// <summary>
/// 用户退出
/// </summary>
public void LoginOut()
{
Session.Abandon();
HttpCookie cookie = new HttpCookie(cookieKey);
cookie["UserID"] = string.Empty;
cookie["UserName"] = string.Empty;
cookie["Password"] = string.Empty;
cookie.Expires = DateTime.MinValue;
try
{
HttpContext.Current.Response.Cookies.Add(cookie);
}
catch
{
Response.Cookies.Add(cookie);
}
}
}