cookie登錄后同域名下的網(wǎng)站保持相同的登錄狀態(tài)。
登錄
PRivate void SetAuthCookie(string userId, bool createPersistentCookie)
{
var ticket = new FormsAuthenticationTicket(2, userId, DateTime.Now, DateTime.Now.AddDays(7), true, "", FormsAuthentication.FormsCookiePath); string ticketEncrypted = FormsAuthentication.Encrypt(ticket); HttpCookie cookie; if (createPersistentCookie)//是否在設(shè)置的過期時間內(nèi)一直有效 { cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted) { HttpOnly = true, Path = FormsAuthentication.FormsCookiePath, Secure = FormsAuthentication.RequireSSL, Expires = ticket.Expiration, Domain = "VEVb.com"http://這里設(shè)置認證的域名,同域名下包括子域名如aa.VEVb.com或bb.VEVb.com都保持相同的登錄狀態(tài) }; } else { cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted) { HttpOnly = true, Path = FormsAuthentication.FormsCookiePath, Secure = FormsAuthentication.RequireSSL, //Expires = ticket.Expiration,//無過期時間的,瀏覽器關(guān)閉后失效 Domain = "VEVb.com" }; } HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); HttpContext.Current.Response.Cookies.Add(cookie);
}
這樣登錄后,在同域名下的任何頁面都可以得到用戶狀態(tài)
判斷用戶是否登錄
public bool IsAuthenticated{ get { bool isPass = System.Web.HttpContext.Current.User.Identity.IsAuthenticated; if (!isPass) SignOut(); return isPass; }}
得到當前的用戶名
public string GetCurrentUserId(){ return _httpContext.User.Identity.Name;}
新聞熱點
疑難解答