在很多asp.net項目中,都會采用forms認證,其內部的機制就是把用戶數據加密后保存在一個基於cookie的票據FormsAuthenticationTicket中。我所在公司是好幾家門店的,項目一上線之后,其中有一家門店,報告上來說:登錄頁面打得開,就是登錄不了。起初還以為是用戶輸入有誤,后來親自測試之后,發現問題大了。如下是登錄頁面的代碼:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, count, DateTime.Now, DateTime.Now.AddMinutes(10), false, ""); FormsAuthentication.SetAuthCooki(count,true); Response.Redirect("~/main.aspx");
webconfig代碼:
<authentication mode="Forms"> <forms name="landrise_aspnet" path="/" loginUrl="~/Login.aspx" timeout="20" defaultUrl="~/Login.aspx"/> </authentication>
main.aspx頁面的代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
else
{
string user = Context.User.Identity.Name;
}
}
為了避免用戶名和密碼輸錯,我把驗證用戶名和密碼程序去掉
用別的門店測試和我自己電腦上IE測試,均都可以轉入main.aspx頁面,但是用問題店就不可以。本人自己IE測試,都可以進入main.aspx
現在用問題門店的電腦分別用火狐,IE6,chrome測試
后來我考濾到有可能是機器系統的原因,然后我用易車網,汽車之家測試,這兩個網站也是用asp.net開發的,也是用了forms認證,用問題門店的電腦登錄這兩個網頁
都沒有任何問題,說明電腦的cookies是沒有問題的。我再用Request.Browser.Cookies 和 Request.Browser.SupportsRedirectWithCookie。進行測試
均為true;問題始終沒有解決。還有一個奇怪的現象,有一段時間,用谷歌瀏覽器居然好了,再次編譯又不行,當然這個現象只出現了兩次。
結論:
1、我懷疑forms認證是否有bug。
2、如果電腦系統問題,易車網,汽車之后為何可以?
3、單步測試之中,user.Identity.Name一直為空。而且在所有電腦上都有可以。
4、Context.User.Identity.IsAuthenticated在問題門店瀏覽器上一直為false,正常電腦上IE,火狐上測試為true。
問題解決:
有可能是問題門店的機器cookie異常,每次清除一下就是可以重新登錄。后來在
Vincent Yang(水平不錯)
的建議下,改用cookieless="useUrl"這樣就解決了。
用了AutoDetect還是不行,說明這個cookie是沒有被禁用的,可能出現異常。
最新的一項測試:
代碼改成:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, count, DateTime.Now, DateTime.Now.AddMinutes(10), false, ""); string encTicket = FormsAuthentication.Encrypt(ticket); // FormsAuthentication.SetAuthCookie(count, true); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); Response.Redirect("~/main.aspx");
然后在web.config中把cookieless="useurl"改成cookieless="AutoDetect",這樣又起作用了,我建議還是用這種方法。如果
userUrl的話,C#代碼還是要改成FormsAuthentication.SetAuthCookie(count, true);