關於Forms 驗證的完整解決方案
HttpContext.Current.User.Identity.IsAuthenticated=false;
HttpContext.Current.User.Identity.Name==""
解釋:當用戶登入時,伺服器為確認客戶端通過驗證要通過cookie向客戶端寫驗證(Authenticat)資訊,在登入頁面剛驗證完成後伺服器還沒有把cookie 回發到Client,所以會沒有值,當伺服器第二次Response的時候,就會從客戶端讀取Cookie,要想有此Cookie還要在web.config檔案中配置相應的引數
<system.web>
<authentication mode="Forms">
<forms domain="bokoAdmin" timeout="20" loginUrl="Login.aspx" path="/"></forms>
<authorization>
<allow users="*"/>
</authorization>
<system.web>
程式驗證:
if (Membership.ValidateUser(tbx_username.Text.TrimEnd(), tbx_password.Text.TrimEnd()))
{
FormsAuthentication.SetAuthCookie(tbx_username.Text.TrimEnd(), true,FormsAuthentication.FormsCookiePath);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, tbx_username.Text, DateTime.Now, DateTime.Now.AddMinutes(20), false, tbx_username.Text);
// generate new identity
FormsIdentity identity = new FormsIdentity(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
// write to client.
Response.Cookies.Add(cookie);
}
其中加粗體為主要語句,有此一句就可以實現HttpContext.Current.User.Identity.IsAuthenticated=true;