使用cookie获取用户信息,长时间不用重新登录
在login页面:
SaveCookie(FormsAuthentication.GetAuthCookie(model.UserName, false), 90)
public static void SaveCookie(HttpCookie cookie, int expireDays)
{
string cookieDomain = "";
string currentURL = HttpContext.Current.Request.Url.AbsoluteUri;
Regex matchNotTLD = new Regex("[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if ((matchNotTLD.IsMatch(cookieDomain)) && (currentURL.IndexOf(cookieDomain) > -1))
{
cookie.Path = "/";
cookie.Domain = cookieDomain;
}
cookie.Expires = DateTime.Now.AddDays(expireDays);
HttpContext.Current.Response.Cookies.Add(cookie);
}
在HttpModule : IHttpModule中获取cookie
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.User.Identity.Name;
......}
在本机用visual2008调试时, HttpContext.Current.User.Identity.Name隔天都可以获取用户信息,但是发布到服务器空间时,过几十分钟后就获取不到了,必须重新登录。